package com.jrx.anytxn.reporting.service.impl;

import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.FileUtils;
import com.jrx.anytxn.common.uitl.StringUtils;
import com.jrx.anytxn.customer.dto.customer.AddressInfoRes;
import com.jrx.anytxn.customer.dto.customer.CustomerFirstLevelRes;
import com.jrx.anytxn.customer.dto.customer.CustomerRes;
import com.jrx.anytxn.customer.entity.*;
import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerAddressInfoMapper;
import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerContactInfoMapper;
import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerLimitInfoMapper;
import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerSecondLevelMapper;
import com.jrx.anytxn.customer.service.IBankCardService;
import com.jrx.anytxn.customer.service.ICustomerService;
import com.jrx.anytxn.param.dto.product.PrPenaltyRateTableRes;
import com.jrx.anytxn.param.dto.system.SystemParameterRes;
import com.jrx.anytxn.param.entity.BtBatchStatus;
import com.jrx.anytxn.param.entity.PrCreditLimitMapping;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.entity.PrProductTable;
import com.jrx.anytxn.param.mapper.ext.ExtBtBatchStatusMapper;
import com.jrx.anytxn.param.service.limit.ICreditLimitMappingService;
import com.jrx.anytxn.param.service.limit.ICreditLimitTypeService;
import com.jrx.anytxn.param.service.ntfs.ICreateTskdFileSampleSimple;
import com.jrx.anytxn.param.service.product.IPrPenaltyRateTableService;
import com.jrx.anytxn.param.service.product.IProductTableService;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.param.service.system.ISystemParameterService;
import com.jrx.anytxn.param.utils.TargzUtil;
import com.jrx.anytxn.reporting.constant.ReportingConstant;
import com.jrx.anytxn.reporting.service.IUnionFileService;
import com.jrx.anytxn.transaction.bean.DebtBean;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.*;
import com.jrx.anytxn.transaction.mapper.ext.*;
import com.jrx.anytxn.transaction.service.IDebtCalculationService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.util.*;

/**
 * 联盟相关文件处理类
 */
@Service
public class UnionFileServiceImpl implements IUnionFileService {

    private static final Logger logger = LoggerFactory.getLogger(UnionFileServiceImpl.class);

    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private ICustomerService customerService;
    @Resource
    private ExtAmLoanMainInfoMapper extAmLoanMainInfoMapper;
    @Autowired
    private ICreditLimitMappingService creditLimitMappingService;
    @Autowired
    private IProductTableService productTableService;
    @Resource
    private ExtTlPaymentAllocationLogMapper extTlPaymentAllocationLogMapper;
    @Resource
    private ExtAmLoanAccountInfoMapper extAmLoanAccountInfoMapper;
    @Resource
    private ExtAmRepaymentPlanInfoMapper extAmRepaymentPlanInfoMapper;
    @Autowired
    private IBankCardService bankCardService;
    @Autowired
    private IDebtCalculationService debtCalculationService;
    @Resource
    private ExtAmInterestAccrualInfoMapper extAmInterestAccrualInfoMapper;
    @Resource
    private ExtTlPaymentMappingMapper extTlPaymentMappingMapper;
    @Autowired
    private IPrPenaltyRateTableService prPenaltyRateTableService;
    @Autowired
    private ICreateTskdFileSampleSimple createTskdFileSampleSimple;
    @Resource
    private ExtCmCustomerAddressInfoMapper extCmCustomerAddressInfoMapper;
    @Resource
    private ExtTlLoanClassifyChangeMapper extTlLoanClassifyChangeMapper;
    @Resource
    private ExtAmDelinquencyInfoMapper extAmDelinquencyInfoMapper;
    @Resource
    private ExtCmCustomerLimitInfoMapper extCmCustomerLimitInfoMapper;
    @Resource
    private ExtAmAccountMainInfoMapper extAmAccountMainInfoMapper;
    @Resource
    private ExtTlDisbursementLogMapper extTlDisbursementLogMapper;
    @Resource
    private ExtCmCustomerContactInfoMapper extCmCustomerContactInfoMapper;
    @Autowired
    private ISystemParameterService systemParameterService;
    @Autowired
    private ICreditLimitTypeService creditLimitTypeService;
    @Resource
    private ExtTlThirdPartyPaymentMapper extTlThirdPartyPaymentMapper;
    @Resource
    private ExtTlPaymentLogMapper extTlPaymentLogMapper;
    @Resource
    private ExtBtBatchStatusMapper extBtBatchStatusMapper;
    @Resource
    private ExtCmCustomerSecondLevelMapper extCmCustomerSecondLevelMapper;

    @Override
    public void createDirectoriesAndFile(String basePath,String fileName,String fileType) {

        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);
        String toDay = DateUtils.format(org.getToday(),"yyyyMMdd");

        String collectionFileName = "";
        if(ReportingConstant.UNION_LS_TENANT_ID.equals(org.getTenantId())){
            collectionFileName = "JLCLOUD_" + fileType+ "_" + toDay + "_" + fileName + ".del";
        }else{
            collectionFileName = fileType+ "_" + toDay + "_" + fileName + ".del";
        }

        String filePath = basePath + org.getTenantId() + File.separator + toDay + File.separator;

        Path reportingFile = Paths.get(filePath + collectionFileName);
        Path pFile = Paths.get(filePath);

        //文件存在，删除文件
        if (reportingFile.toFile().exists()) {
            try {
                Files.delete(reportingFile);
            }catch (IOException e) {
                //因为listener实现的原接口未对异常做处理，所以不能抛出普通异常。
                throw new RuntimeException(e);
            }
        }

        //判断文件夹是否存在
        if (!pFile.toFile().isDirectory()) {
            //创建文件夹
            try {
                Files.createDirectories(pFile);
            } catch (IOException e) {
                logger.error("创建联盟文件目录失败",e);
            }
        }
        //创建文件
        try {
            Files.createFile(reportingFile);
        } catch (IOException e) {
            logger.error("创建联盟数整文件失败",e);
        }
    }

    private String subLoanId(String loanId,String tenantId){
        if(StringUtils.isNotBlank(loanId) && ReportingConstant.UNION_DEFAULT_TENANT_ID.equals(tenantId)){
            if(loanId.length()>16){
                return StringUtils.right(loanId,16);
            }
        }
        return loanId;
    }

    @Override
    public String createLoanSerialFileMessage(TlDisbursementLog log) throws TxnException {
        StringBuffer sb = new StringBuffer();
        //1 租户号
        sb.append(log.getTenantId() + ReportingConstant.separator_union);
        //2 借据号
        sb.append(subLoanId(log.getLoanId(),log.getTenantId()) + ReportingConstant.separator_union);
        //3 流水号
        sb.append(log.getSeqNo() + ReportingConstant.separator_union);
        //4 发起时间
        String launchTime = DateUtils.format(log.getBusinessDate(),DateUtils.DATE_PATTERN_ANOTHER);
        sb.append(launchTime + ReportingConstant.separator_union);
        //查询客户信息
        CustomerRes customer = customerService.getCustomerByChannelAndCustomerIdAndTensnId(log.getChannel(),
                log.getCustomerId(),log.getTenantId());
        //5 用户编号
        sb.append(handleCustomerId(customer.getSecondLevel().getCustomerId(),log.getTenantId()) + ReportingConstant.separator_union);
        //6 用户名称
        sb.append(customer.getFirstLevel().getChineseName() + ReportingConstant.separator_union);
        //7 收款用户
        sb.append(customer.getFirstLevel().getChineseName() + ReportingConstant.separator_union);
        //获取订单信息
        AmLoanMainInfo amLoanMainInfo = extAmLoanMainInfoMapper.selectByLoanIdAndCusId(log.getLoanId(),log.getCustomerId(),log.getTenantId());
        //8 商户编号
        SystemParameterRes res1 = systemParameterService.findByParamCode(ReportingConstant.SYS_MERCHANT_ID,amLoanMainInfo.getTenantId());
        sb.append(res1.getParamValue() + ReportingConstant.separator_union);
        //9 门店Id
        sb.append("" + ReportingConstant.separator_union);
        //10 合作商编号
        sb.append((amLoanMainInfo.getPartnerId() == null ? "":amLoanMainInfo.getPartnerId()) + ReportingConstant.separator_union);
        //11 放款类型 1 线上
        sb.append("1" + ReportingConstant.separator_union);
        //12 放款方式 0自主支付 1受托支付
        if(ReportingConstant.UNION_DEFAULT_TENANT_ID.equals(log.getTenantId())){
            sb.append("0" + ReportingConstant.separator_union);
        }else{
            sb.append(log.getEntrustedPayment() + ReportingConstant.separator_union);
        }
        //13 放款金额
        sb.append(log.getAmount() + ReportingConstant.separator_union);
        //14 一次性手续费
        sb.append("0" + ReportingConstant.separator_union);
        //15 合作费
        sb.append("0" + ReportingConstant.separator_union);
        //16 放款状态 EnumLoanSerialStatus 1:放款处理中2:已放款3:失败
        if(ReportingConstant.DISBURSEMENT_LOG_SUM_STATUS_S.equals(log.getSumStatus())){
            sb.append("2" + ReportingConstant.separator_union);
        }else if(ReportingConstant.DISBURSEMENT_LOG_SUM_STATUS_F.equals(log.getSumStatus())){
            sb.append("3" + ReportingConstant.separator_union);
        }else{
            sb.append("0" + ReportingConstant.separator_union);
        }
        //17 结算流水
        sb.append("" + ReportingConstant.separator_union);
        //18 结算明细号
        sb.append("" + ReportingConstant.separator_union);
        //19 结算时间
        sb.append("" + ReportingConstant.separator_union);
        //20 结算状态
        sb.append("" + ReportingConstant.separator_union);
        //21 创建时间
        sb.append((DateUtils.format(log.getCreateTime(),DateUtils.DATE_PATTERN_ANOTHER)) + ReportingConstant.separator_union);
        //22 更新时间
        sb.append("" + ReportingConstant.separator_union);
        //23 源系统标识
        SystemParameterRes sourceRes = systemParameterService.findByParamCode(ReportingConstant.SYS_SOURCE_ID,amLoanMainInfo.getTenantId());
        sb.append(sourceRes.getParamValue() + ReportingConstant.separator_union);
        //24 核心记账日期 业务日期
        sb.append((DateUtils.format(log.getBusinessDate(),DateUtils.DATE_PATTERN_ANOTHER)) + ReportingConstant.separator_union);
        //25 业务办理机构
        SystemParameterRes orgRes = systemParameterService.findByParamCode(ReportingConstant.SYS_ORGNO,amLoanMainInfo.getTenantId());
        sb.append(orgRes.getParamValue() + ReportingConstant.separator_union);
        //26 贷款分户账号
        sb.append("" + ReportingConstant.separator_union);
        //27 信贷合同号
        sb.append(subLoanId(amLoanMainInfo.getLoanId(),amLoanMainInfo.getTenantId()) + ReportingConstant.separator_union);
        //28 核心客户编号
        sb.append((customer.getFirstLevel().getEcifId() == null ? "" : customer.getFirstLevel().getEcifId()) + ReportingConstant.separator_union);
        //29 明细科目编号
        SystemParameterRes aclgRes = null;
        if(ReportingConstant.UNION_DEFAULT_TENANT_ID.equals(amLoanMainInfo.getTenantId())){
            aclgRes = systemParameterService.findByParamCode(ReportingConstant.TA_SYS_ACLG_NO,amLoanMainInfo.getTenantId());
        }else if(ReportingConstant.UNION_LS_TENANT_ID.equals(amLoanMainInfo.getTenantId())){
            //需要区分经营 消费贷
            if(amLoanMainInfo.getLoanType().equals(ReportingConstant.LOAN_TYPE_6)){
                aclgRes = systemParameterService.findByParamCode(ReportingConstant.LS_SYS_ACLG_NO_JY,amLoanMainInfo.getTenantId());
            }else{
                aclgRes = systemParameterService.findByParamCode(ReportingConstant.LS_SYS_ACLG_NO_XF,amLoanMainInfo.getTenantId());
            }
        }
        if(null != aclgRes){
            sb.append(aclgRes.getParamValue() + ReportingConstant.separator_union);
        }else{
            sb.append("" + ReportingConstant.separator_union);
        }
        //30 账户名称
        sb.append(log.getPayeeName() + ReportingConstant.separator_union);
        //31 交易类型 00 贷款发放
        sb.append("00" + ReportingConstant.separator_union);
        //32 交易借贷标志 C-贷，D-借
        sb.append("D" + ReportingConstant.separator_union);
        //33 账户余额 客户剩余额度
        //根据产品ID查询产品对应的节点
        String limitId = creditLimitMappingService.getLimitId(log.getOrganizationId(),log.getChannel(),log.getProductId(),log.getTenantId());
        String useMode = creditLimitTypeService.getUserModal(limitId,log.getOrganizationId(),log.getTenantId());
        CmCustomerLimitInfo cmCustomerLimitInfo = null;
        if(ReportingConstant.USE_MODE_0.equals(useMode)){
            cmCustomerLimitInfo = extCmCustomerLimitInfoMapper.selectByTenIdAndCusIdAndLimitId(log.getTenantId(),log.getCustomerId(),limitId);
        }else{
            cmCustomerLimitInfo = extCmCustomerLimitInfoMapper.selectCustomerLimitInfo(log.getCustomerId(),log.getOrganizationId(),limitId,amLoanMainInfo.getContractNumber(),log.getTenantId());
        }
        if(null == cmCustomerLimitInfo){
            sb.append(BigDecimal.ZERO.setScale(4,BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
        }else{
            sb.append(cmCustomerLimitInfo.getLimitAvailable().setScale(4,BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
        }
        //34 对方账号
        SystemParameterRes acctNo = systemParameterService.findByParamCode(ReportingConstant.SYS_OPPT_ACCT_NO,amLoanMainInfo.getTenantId());
        sb.append(acctNo.getParamValue() + ReportingConstant.separator_union);
        //35 对方户名
        SystemParameterRes acctName = systemParameterService.findByParamCode(ReportingConstant.SYS_OPPT_ACCT_NAME,amLoanMainInfo.getTenantId());
        sb.append(acctName.getParamValue() + ReportingConstant.separator_union);
        //36 对方行号
        SystemParameterRes bankNo = systemParameterService.findByParamCode(ReportingConstant.SYS_OPPT_BANK_NO,amLoanMainInfo.getTenantId());
        sb.append(bankNo.getParamValue() + ReportingConstant.separator_union);
        //37 对方行名
        SystemParameterRes bankName = systemParameterService.findByParamCode(ReportingConstant.SYS_OPPT_BANK_NAME,amLoanMainInfo.getTenantId());
        sb.append(bankName.getParamValue() + ReportingConstant.separator_union);
        //38 交易渠道 00 其他
        sb.append("00" + ReportingConstant.separator_union);
        //39 币种
        sb.append(log.getCurrency() + ReportingConstant.separator_union);
        //40 交易柜员号
        SystemParameterRes custMgNo = systemParameterService.findByParamCode(ReportingConstant.SYS_CUST_MG_NO,amLoanMainInfo.getTenantId());
        sb.append(custMgNo.getParamValue() + ReportingConstant.separator_union);
        //41 授权柜员号
        sb.append(custMgNo.getParamValue() + ReportingConstant.separator_union);
        //42 现转标志 2 转账
        sb.append("2" + ReportingConstant.separator_union);
        //43 贷款发放类别 D01 -正常发放 金融机构正常发放贷款业务。
        sb.append("D01" + ReportingConstant.separator_union);
        //44 贷款收回类别
        sb.append("" + ReportingConstant.separator_union);
        //45 冲补抹标志 1 正常
        sb.append("1" + ReportingConstant.separator_union);
        //46 交易码
        sb.append("" + ReportingConstant.separator_union);
        //47 交易描述
        sb.append("");

        return sb.toString();
    }

    @Override
    public String createUnionCustInfoFileMessage(CmCustomerFirstLevel cmCustomerFirstLevel) throws TxnException {
        StringBuffer sb = new StringBuffer();

        int limitCount = extCmCustomerLimitInfoMapper.selectCountLimit(cmCustomerFirstLevel.getCustomerId(),cmCustomerFirstLevel.getOrganizationId(),
                cmCustomerFirstLevel.getTenantId());

        //过滤掉没有额度的客户
        if (limitCount <= 0){
            return null;
        }

        //1 客户ID
        sb.append(handleCustomerId(cmCustomerFirstLevel.getCustomerId(),cmCustomerFirstLevel.getTenantId()) + ReportingConstant.separator_union);
        //2 客户类型 200 个人客户
        sb.append("200" + ReportingConstant.separator_union);
        //3 激活状态  1, 有效
        sb.append("1" + ReportingConstant.separator_union);
        //4 记录状态 1 启用
        sb.append("1" + ReportingConstant.separator_union);
        //5 是否关系人客户 0 否
        sb.append("0" + ReportingConstant.separator_union);
        //6 名单状态 1 白名单
        sb.append("0" + ReportingConstant.separator_union);
        //7 客户经理ID
        SystemParameterRes custMgNo = systemParameterService.findByParamCode(ReportingConstant.SYS_CUST_MG_NO,cmCustomerFirstLevel.getTenantId());
        sb.append(custMgNo.getParamValue() + ReportingConstant.separator_union);
        //8 客户经理类型
        sb.append("" + ReportingConstant.separator_union);
        //9 信用等级
        sb.append("" + ReportingConstant.separator_union);
        //10 实名认证标志 1 是
        sb.append("1" + ReportingConstant.separator_union);
        //11 创建日期
        String createTime = DateUtils.format(cmCustomerFirstLevel.getCreateTime(),DateUtils.DATE_PATTERN_ANOTHER);
        sb.append(createTime + ReportingConstant.separator_union);
        //12 创建人
        sb.append("" + ReportingConstant.separator_union);
        //13 修改日期
        sb.append("" + ReportingConstant.separator_union);
        //14 修改人
        sb.append("" + ReportingConstant.separator_union);
        //15 租户ID
        sb.append(cmCustomerFirstLevel.getTenantId() + ReportingConstant.separator_union);
        //16 源系统标识
        SystemParameterRes sourceId = systemParameterService.findByParamCode(ReportingConstant.SYS_SOURCE_ID,cmCustomerFirstLevel.getTenantId());
        sb.append(sourceId.getParamValue());

        return sb.toString();
    }

    @Override
    public String createCreditInfoFileMessage(CmCustomerLimitInfo cmCustomerLimitInfo) throws TxnException {
        StringBuffer sb = new StringBuffer();
        //1 租户号
        sb.append(cmCustomerLimitInfo.getTenantId() + ReportingConstant.separator_union);
        //2 授信编号 客户号+额度表id  非循环一次性 合同号
        if(ReportingConstant.USE_MODE_0.equals(cmCustomerLimitInfo.getUseMode())) {
            sb.append((handleCustomerId(cmCustomerLimitInfo.getCustomerId(),cmCustomerLimitInfo.getTenantId()) + cmCustomerLimitInfo.getLimitId()) + ReportingConstant.separator_union);
        }else{
            sb.append(cmCustomerLimitInfo.getContractNumber() + ReportingConstant.separator_union);
        }
        //3 用户编号
        sb.append(handleCustomerId(cmCustomerLimitInfo.getCustomerId(),cmCustomerLimitInfo.getTenantId()) + ReportingConstant.separator_union);
        //根据额度节点ID，
        List<PrCreditLimitMapping> prCreditLimitMappingList = creditLimitMappingService.selectByTenantIdAndChannel(cmCustomerLimitInfo.getOrganizationId(),cmCustomerLimitInfo.getChannel(),
                cmCustomerLimitInfo.getTenantId(),cmCustomerLimitInfo.getLimitId());
        //根据产品ID查询产品信息
        PrProductTable prProductTable = productTableService.findProByProIdAndOrgId(prCreditLimitMappingList.get(0).getProductId(),cmCustomerLimitInfo.getOrganizationId(),cmCustomerLimitInfo.getTenantId());
        //4 产品主键
        sb.append(prProductTable.getId() + ReportingConstant.separator_union);
        //5 授信产品id
        if(ReportingConstant.UNION_DEFAULT_TENANT_ID.equals(cmCustomerLimitInfo.getTenantId())){
            SystemParameterRes proRes = systemParameterService.findByParamCode(ReportingConstant.SYS_PRODUCT_ID,cmCustomerLimitInfo.getTenantId());
            sb.append(proRes.getParamValue() + ReportingConstant.separator_union);
        }else{
            sb.append(prProductTable.getProductId() + ReportingConstant.separator_union);
        }

        //6 授信产品名称
        sb.append(prProductTable.getChineseName() + ReportingConstant.separator_union);
        //7 授信额度
        sb.append(cmCustomerLimitInfo.getLimitAmount().setScale(4,BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
        //8 冻结额度
        if(ReportingConstant.LIMIT_STATUS_2.equals(cmCustomerLimitInfo.getLimitStatus())){
            sb.append(cmCustomerLimitInfo.getLimitAmount() + ReportingConstant.separator_union);
        }else{
            sb.append("0" + ReportingConstant.separator_union);
        }
        //9 使用额度
        sb.append(cmCustomerLimitInfo.getLimitUsed().setScale(4,BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
        //10 历史使用额度
        sb.append("0" + ReportingConstant.separator_union);
        //11 暂封额度
        sb.append("0" + ReportingConstant.separator_union);
        //12 额度类型  1:循环0:不可循环;
        if(ReportingConstant.USE_MODE_0.equals(cmCustomerLimitInfo.getUseMode())){
            sb.append("1" + ReportingConstant.separator_union);
        }else{
            sb.append("0" + ReportingConstant.separator_union);
        }
        //13 生效时间
        if(null != cmCustomerLimitInfo.getLimitEffectiveDate()){
            String effectiveDate = DateUtils.format(cmCustomerLimitInfo.getLimitEffectiveDate(),DateUtils.DATE_PATTERN_ANOTHER);
            sb.append(effectiveDate + ReportingConstant.separator_union);
        }else{
            sb.append("" + ReportingConstant.separator_union);
        }
        //14 失效时间
        if(null != cmCustomerLimitInfo.getLimitExpiryDate()){
            String effectiveDate = DateUtils.format(cmCustomerLimitInfo.getLimitExpiryDate(),"yyyyMMdd HH:mm:ss");
            sb.append(effectiveDate + ReportingConstant.separator_union);
        }else{
            sb.append("" + ReportingConstant.separator_union);
        }
        //15 额度状态
        sb.append("0" + ReportingConstant.separator_union);
        //16 生效状态 EnumBool 0:否1：是
        if(ReportingConstant.LIMIT_STATUS_0.equals(cmCustomerLimitInfo.getLimitStatus())){
            sb.append("0" + ReportingConstant.separator_union);
        }else{
            sb.append("1" + ReportingConstant.separator_union);
        }
        //17 额度恢复方式 0:本金归还即恢复 1:结清恢复 非循环额度送空
        if(ReportingConstant.UNION_DEFAULT_TENANT_ID.equals(cmCustomerLimitInfo.getTenantId())){
            sb.append("0" + ReportingConstant.separator_union);
        }else{
            sb.append("" + ReportingConstant.separator_union);
        }
        //18 创建时间
        String createTime = DateUtils.format(cmCustomerLimitInfo.getCreateTime(),"yyyyMMdd");
        sb.append(createTime + ReportingConstant.separator_union);
        //19 更新时间
        sb.append("" + ReportingConstant.separator_union);
        //20 源系统标识
        SystemParameterRes sourceRes = systemParameterService.findByParamCode(ReportingConstant.SYS_SOURCE_ID,cmCustomerLimitInfo.getTenantId());
        sb.append(sourceRes.getParamValue() + ReportingConstant.separator_union);
        //21 业务办理机构
        SystemParameterRes orgNo = systemParameterService.findByParamCode(ReportingConstant.SYS_ORGNO,cmCustomerLimitInfo.getTenantId());
        sb.append(orgNo.getParamValue() + ReportingConstant.separator_union);
        //22 授信种类 04-个人客户授信
        sb.append("04" + ReportingConstant.separator_union);
        //23 核心客户编号
        //查询客户信息
        CustomerRes customer = customerService.getCustomerByChannelAndCustomerIdAndTensnId(cmCustomerLimitInfo.getChannel(),
                cmCustomerLimitInfo.getCustomerId(),cmCustomerLimitInfo.getTenantId());
        sb.append((customer.getFirstLevel().getEcifId() == null ? "": customer.getFirstLevel().getEcifId()) + ReportingConstant.separator_union);
        //24 单位币种
        sb.append("CNY" + ReportingConstant.separator_union);
        //25 首次授信日期
        String createDate = DateUtils.format(cmCustomerLimitInfo.getCreateTime(),DateUtils.DATE_PATTERN_ANOTHER);
        sb.append(createDate + ReportingConstant.separator_union);
        //26 授信期限 单位：天
        if(null != cmCustomerLimitInfo.getLimitEffectiveDate() && null != cmCustomerLimitInfo.getLimitExpiryDate()){
            int days = DateUtils.getDaysBetween(cmCustomerLimitInfo.getLimitExpiryDate(), cmCustomerLimitInfo.getLimitEffectiveDate());
            sb.append(days + ReportingConstant.separator_union);
        }else{
            sb.append("" + ReportingConstant.separator_union);
        }
        //27 决策单意见
        sb.append("" + ReportingConstant.separator_union);
        //28 最终审批人
        SystemParameterRes custMgNo = systemParameterService.findByParamCode(ReportingConstant.SYS_CUST_MG_NO,cmCustomerLimitInfo.getTenantId());
        sb.append(custMgNo.getParamValue() + ReportingConstant.separator_union);
        //29 临时额度
        sb.append("0" + ReportingConstant.separator_union);
        //30 是否临时额度
        sb.append("0" + ReportingConstant.separator_union);
        //31 临时额度开始日期
        sb.append((cmCustomerLimitInfo.getLimitTempStartDate() == null ? "":DateUtils.format(cmCustomerLimitInfo.getLimitTempStartDate(),DateUtils.DATE_PATTERN_ANOTHER)) + ReportingConstant.separator_union);
        //32 临时额度结束日期
        sb.append((cmCustomerLimitInfo.getLimitTempEndDate() == null ? "":DateUtils.format(cmCustomerLimitInfo.getLimitTempEndDate(),DateUtils.DATE_PATTERN_ANOTHER)) + ReportingConstant.separator_union);
        //33 授信员工号
        sb.append(custMgNo.getParamValue() + ReportingConstant.separator_union);
        //34 源系统表标识
        sb.append(sourceRes.getParamValue());

        return sb.toString();
    }

    @Override
    public String createUserContactFileMessage(CmCustomerFirstLevel cmCustomerFirstLevel) throws TxnException {
        //按照时间查询客户二级信息表 判断是否需要生成对应文件
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(cmCustomerFirstLevel.getOrganizationId());

        BtBatchStatus statuses = extBtBatchStatusMapper.selectByStatusAndJobName(ReportingConstant.BATCH_SATTUS_2,
                ReportingConstant.CUTOVER_END,org.getTenantId(),org.getToday());
        Date updateTime = null;
        if(null != statuses){
            updateTime = statuses.getCreateTime();
        }

        CmCustomerSecondLevel cmCustomerSecondLevel = extCmCustomerSecondLevelMapper.selectByUpdateTimeAndCustId(cmCustomerFirstLevel.getTenantId(),cmCustomerFirstLevel.getCustomerId(),
                updateTime, null);

        if(cmCustomerSecondLevel == null){
            return null;
        }

        StringBuffer sb = new StringBuffer();
        //1 联系点ID customer_id + USER_id
        sb.append((handleCustomerId(cmCustomerSecondLevel.getCustomerId(),cmCustomerSecondLevel.getTenantId()) + cmCustomerSecondLevel.getUserId()) + ReportingConstant.separator_union);
        //2 客户角色ID
        sb.append("" + ReportingConstant.separator_union);
        //3 客户ID
        sb.append(handleCustomerId(cmCustomerSecondLevel.getCustomerId(),cmCustomerSecondLevel.getTenantId()) + ReportingConstant.separator_union);
        //4 联系点类型
        sb.append("1" + ReportingConstant.separator_union);
        //5 联系点状态
        sb.append("3" + ReportingConstant.separator_union);
        //6 是否默认联系点
        sb.append("" + ReportingConstant.separator_union);
        //7 是否验证
        sb.append("" + ReportingConstant.separator_union);
        //8 创建时间
        sb.append("" + ReportingConstant.separator_union);
        //9 创建人
        sb.append("" + ReportingConstant.separator_union);
        //10 修改时间
        sb.append("" + ReportingConstant.separator_union);
        //11 修改人
        sb.append("" + ReportingConstant.separator_union);
        //12 租户ID
        sb.append(cmCustomerSecondLevel.getTenantId() + ReportingConstant.separator_union);
        //13 源系统标识
        SystemParameterRes sourceRes = systemParameterService.findByParamCode(ReportingConstant.SYS_SOURCE_ID,cmCustomerSecondLevel.getTenantId());
        sb.append(sourceRes.getParamValue());

        return sb.toString();
    }

    @Override
    public String createLoanProductFileMessage(AmLoanMainInfo amLoanMainInfo) throws TxnException {
        AmLoanAccountInfo amLoanAccountInfo = extAmLoanAccountInfoMapper.selectByLoanId(amLoanMainInfo.getLoanId(),amLoanMainInfo.getCustomerId(),amLoanMainInfo.getTenantId());

        if(ReportingConstant.ACCOUNT_STATUS_0.equals(amLoanAccountInfo.getAccountStatus())||
                ReportingConstant.ACCOUNT_STATUS_9.equals(amLoanAccountInfo.getAccountStatus())){
            return null;
        }

        StringBuffer sb = new StringBuffer();

        DecimalFormat df2 = new DecimalFormat("0.000000");

        //1 租户号
        sb.append(amLoanMainInfo.getTenantId() + ReportingConstant.separator_union);
        //2 借据编号
        sb.append(subLoanId(amLoanMainInfo.getLoanId(),amLoanMainInfo.getTenantId()) + ReportingConstant.separator_union);
        //查询产品信息
        PrProductTable productTable = productTableService.findProByProIdAndOrgId(amLoanMainInfo.getProductId(),amLoanMainInfo.getOrganizationId(),amLoanMainInfo.getTenantId());
        //3 产品主键
        sb.append(productTable.getId() + ReportingConstant.separator_union);
        //4 产品编号
        if(ReportingConstant.UNION_DEFAULT_TENANT_ID.equals(amLoanMainInfo.getTenantId())){
            SystemParameterRes proRes = systemParameterService.findByParamCode(ReportingConstant.SYS_PRODUCT_ID,amLoanMainInfo.getTenantId());
            sb.append(proRes.getParamValue() + ReportingConstant.separator_union);
        }else{
            sb.append(productTable.getProductId() + ReportingConstant.separator_union);
        }
        //5 产品名称
        sb.append(productTable.getChineseName() + ReportingConstant.separator_union);
        //6 还款方式
        String paymentMode="";// 行方还款方式1:等额本息2:等额本金3:等本等息4:按期付息到期还本5:随借随还，按月付息，到期还本6:到期一次性还本付息7:按日计息，等额还款
        switch (amLoanMainInfo.getAmortMethodTableId()){
            case ReportingConstant.PRIN_CHARGE_OPTION_EPEI ://TXN 01 分期付款（等本等息）
                paymentMode="3";
                break;
            case ReportingConstant.PRIN_CHARGE_OPTION_EPI ://TXN 02 等额本息
                paymentMode="1";
                break;
            case ReportingConstant.PRIN_CHARGE_OPTION_EP ://TXN 03 等额本金
                paymentMode="2";
                break;
            case ReportingConstant.PRIN_CHARGE_OPTION_MONTHLY_INTPAY ://TXN 06 按期付息，到期还本
                paymentMode="4";
                break;
            case ReportingConstant.PRIN_CHARGE_OPTION_MI_YP ://TXN 08 按月付息，按年还本
                paymentMode="5";
                break;
            case ReportingConstant.PRIN_CHARGE_OPTION_INTPAY ://TXN 09 随见随还 利随本清
                paymentMode="";
                break;
        }
        sb.append(paymentMode + ReportingConstant.separator_union);
        //7 原始利率
        sb.append(df2.format(amLoanMainInfo.getInterestRate().multiply(new BigDecimal(100))) + ReportingConstant.separator_union);
        //8 还款频率
        sb.append("01" + ReportingConstant.separator_union);
        //9 还款顺序 按利息先
        sb.append("1" + ReportingConstant.separator_union);
        //10 本金收取方式 2 正常
        sb.append("2" + ReportingConstant.separator_union);
        //11 利息收取方式
        sb.append("2" + ReportingConstant.separator_union);
        //12 提前还款后处理方式
        sb.append("2" + ReportingConstant.separator_union);
        //13 提前还款后计息方式
        sb.append("1" + ReportingConstant.separator_union);
        //14 提前还款费用规则
        sb.append("1" + ReportingConstant.separator_union);
        //15 提前还款类型 1:全部 2:部分
        sb.append("" + ReportingConstant.separator_union);
        //16 是否允许提前还款
        sb.append("1" + ReportingConstant.separator_union);
        //17 是否收取提前还款违约金
        sb.append("0" + ReportingConstant.separator_union);
        //18 部分提前还款利息计算方式
        sb.append("0" + ReportingConstant.separator_union);
        //19 是否支持退款
        sb.append("0" + ReportingConstant.separator_union);
        //20 退款资金方向
        sb.append("" + ReportingConstant.separator_union);
        //21 固定日类型 1:否2:是
        sb.append("2" + ReportingConstant.separator_union);
        //22 固定日
        sb.append(amLoanMainInfo.getPaymentDateDd() + ReportingConstant.separator_union);
        //23 首期还款间隔天数
        int days = DateUtils.getDaysBetween(amLoanMainInfo.getFirstPaymentDate(),amLoanMainInfo.getInterestStartDate());
        sb.append(days + ReportingConstant.separator_union);
        //24 末期还款间隔天数
        int days2 = DateUtils.getDaysBetween(amLoanMainInfo.getLastPaymentDate(),amLoanMainInfo.getInterestStartDate());
        sb.append(days2 + ReportingConstant.separator_union);
        //25 是否计算复利 0 否 1 是
        sb.append("1" + ReportingConstant.separator_union);
        //26 宽限日
        sb.append(productTable.getGraceDays() + ReportingConstant.separator_union);
        //27 额外信息
        sb.append("" + ReportingConstant.separator_union);
        //28 创建时间
        sb.append("" + ReportingConstant.separator_union);
        //29 修改时间
        sb.append("" + ReportingConstant.separator_union);
        //30 允许还款提前天数 起息日和结清日的差-1
        sb.append((days2 - 1) + ReportingConstant.separator_union);
        //31 是否允许当月还款
        sb.append("1" + ReportingConstant.separator_union);
        //32 源系统标识
        SystemParameterRes souRes = systemParameterService.findByParamCode(ReportingConstant.SYS_SOURCE_ID,amLoanMainInfo.getTenantId());
        sb.append(souRes.getParamValue());

        return sb.toString();
    }

    @Override
    public List<String> createRepayFileMessage(TlPaymentLog log) throws TxnException {
        //根据还款流水查询映射表
        List<TlPaymentMapping> mappingList = extTlPaymentMappingMapper.selectByPaymentSeqAndCustomerId(log.getSeqNo(),log.getCustomerId(),log.getTenantId());

        List<String> messageList = new ArrayList<>();

        for(TlPaymentMapping tlPaymentMapping : mappingList){
            StringBuffer sb = new StringBuffer();
            //获取贷款账户信息
            AmLoanAccountInfo amLoanAccountInfo = extAmLoanAccountInfoMapper.selectByLoanId(tlPaymentMapping.getLoanId(),log.getCustomerId(),log.getTenantId());
            //获取借据信息
            AmLoanMainInfo amLoanMainInfo = extAmLoanMainInfoMapper.selectByLoanIdAndCusId(tlPaymentMapping.getLoanId(),log.getCustomerId(),log.getTenantId());
            //获取对应期次还款计划
            AmRepaymentPlanInfo castPlan = extAmRepaymentPlanInfoMapper.selectByLoanIdAndBillingTenor(amLoanAccountInfo.getLoanId(),
                    amLoanAccountInfo.getCustomerId(),amLoanAccountInfo.getTenantId(),amLoanAccountInfo.getCastTenor(),
                    Arrays.asList(TransBizConstant.LOAN_PLAN_STATUS_0,TransBizConstant.LOAN_PLAN_STATUS_1, TransBizConstant.LOAN_PLAN_STATUS_2,
                            TransBizConstant.LOAN_PLAN_STATUS_7,TransBizConstant.LOAN_PLAN_STATUS_8,TransBizConstant.LOAN_PLAN_STATUS_6));
            //查询客户信息
            CustomerRes customer = customerService.getCustomerByChannelAndCustomerIdAndTensnId(log.getChannel(),
                    log.getCustomerId(),log.getTenantId());

            //查询还款分配流水表
            List<TlPaymentAllocationLog> tlPaymentAllocationLogList = extTlPaymentAllocationLogMapper.findCustLog(tlPaymentMapping.getLoanId(),
                    tlPaymentMapping.getPaymentSeqNo(),tlPaymentMapping.getCustomerId(),tlPaymentMapping.getTenantId());

            String detailId = null;
            tlPaymentAllocationLogList.sort(Comparator.comparing(TlPaymentAllocationLog::getId));
            for (TlPaymentAllocationLog tllog : tlPaymentAllocationLogList) {
                if (!tllog.getAccountType().equals("08")) {
                    detailId = tllog.getAccountId();
                    break;
                }
            }
            //1 租户号
            sb.append(amLoanAccountInfo.getTenantId() + ReportingConstant.separator_union);
            //2 明细号 原系统TXA_NUMBER
            sb.append(detailId + ReportingConstant.separator_union);
            //3 业务流水
            sb.append("" + ReportingConstant.separator_union);
            //4 合并流水
            sb.append("" + ReportingConstant.separator_union);
            //5 借据号
            sb.append(subLoanId(tlPaymentMapping.getLoanId(),tlPaymentMapping.getTenantId()) + ReportingConstant.separator_union);
            //6 用户编号
            sb.append(handleCustomerId(log.getCustomerId(),log.getTenantId()) + ReportingConstant.separator_union);
            //7 用户姓名
            sb.append(log.getCustomerName() + ReportingConstant.separator_union);
            //8 还款期次（1,2,3格式）
            for(TlPaymentAllocationLog tlPaymentAllocationLog : tlPaymentAllocationLogList){
                if(!tlPaymentAllocationLog.getAccountType().equals("08")){
                    sb.append(tlPaymentAllocationLog.getBillingTenor() + ReportingConstant.separator_union);
                    break ;
                }
            }

            //9 还款类型 EnumLineType 1:线上2:线下;
            sb.append("1" + ReportingConstant.separator_union);
            //10 是否统还 0 否 1 是
            String format = DateUtils.format(castPlan.getPaymentDueDate());
            String format1 = DateUtils.format(log.getBusinessDate());
            if(format.substring(format.length()-2).equals(format1.substring(format1.length()-2))){
                sb.append("0" + ReportingConstant.separator_union);
            }else{
                sb.append("1" + ReportingConstant.separator_union);
            }
            //11 还款操作类型
            if(ReportingConstant.REPAYMENT_TYPE_OVERDUE.equals(log.getPaymentType()) ||
                    ReportingConstant.REPAYMENT_TYPE_BILLOVERDUEPAY.equals(log.getPaymentType())){
                //1 逾期还款
                sb.append("1" + ReportingConstant.separator_union);
            }else if(ReportingConstant.REPAYMENT_TYPE_PAY.equals(log.getPaymentType())){
                //2 正常还款
                sb.append("2" + ReportingConstant.separator_union);
            }else if(ReportingConstant.REPAYMENT_TYPE_PREPAY.equals(log.getPaymentType())||
                    ReportingConstant.REPAYMENT_TYPE_PREPAY_CURR.equals(log.getPaymentType())){
                //3 提前还款
                sb.append("3" + ReportingConstant.separator_union);
            }else if(ReportingConstant.REPAYMENT_TYPE_CMPS.equals(log.getPaymentType())){
                //4 代偿还款
                sb.append("4" + ReportingConstant.separator_union);
            }else {
                sb.append("2" + ReportingConstant.separator_union);
            }
            //12 合作商编号
            sb.append("" + ReportingConstant.separator_union);
            //13 商户号
            sb.append("" + ReportingConstant.separator_union);
            //14 代偿人用户编号
            sb.append("" + ReportingConstant.separator_union);
            //区分成功，处理中
            BigDecimal totalAmount = BigDecimal.ZERO;//总金额
            BigDecimal principalAmount=BigDecimal.ZERO;//本金
            BigDecimal interestAmount=BigDecimal.ZERO;//利息
            BigDecimal penaltyAmount=BigDecimal.ZERO;//罚息
            BigDecimal feeAmount=BigDecimal.ZERO;//费用
            BigDecimal prepayFee=BigDecimal.ZERO;//提前还款手续费
            BigDecimal compountAmount = BigDecimal.ZERO;//复利

            //直接拿09交易账户金额
            for(TlPaymentAllocationLog allocationLog : tlPaymentAllocationLogList){
                if(ReportingConstant.ACCOUNT_TYPE_06.equals(allocationLog.getConnectAccountType())){
                    principalAmount = principalAmount.add(allocationLog.getPostingAmount());
                }
                if(ReportingConstant.ACCOUNT_TYPE_04.equals(allocationLog.getConnectAccountType())){
                    interestAmount = interestAmount.add(allocationLog.getPostingAmount());
                }
                if(ReportingConstant.ACCOUNT_TYPE_11.equals(allocationLog.getConnectAccountType())){
                    penaltyAmount = penaltyAmount.add(allocationLog.getPostingAmount());
                }
                if(ReportingConstant.ACCOUNT_TYPE_12.equals(allocationLog.getConnectAccountType())){
                    compountAmount = compountAmount.add(allocationLog.getPostingAmount());
                }
                //费用计算
                if(allocationLog.getTxnCode().substring(3,4).equals("2")){
                    switch (allocationLog.getTxnCode().substring(5,6)){
                        case "1"://一次性手续费
                            feeAmount = feeAmount.add(allocationLog.getPostingAmount());
                            break;
                        case "2"://分期手续费
                            feeAmount = feeAmount.add(allocationLog.getPostingAmount());
                            break;
                        case "3"://提前还款手续费还款
                            feeAmount = feeAmount.add(allocationLog.getPostingAmount());
                            break;
                        case "4"://提前结清手续费还款
                            prepayFee = prepayFee.add(allocationLog.getPostingAmount());
                            break;
                    }
                }
            }

            totalAmount = principalAmount.add(interestAmount).add(penaltyAmount).add(feeAmount).add(prepayFee).add(compountAmount);
            //15 还款总金额
            sb.append(totalAmount.setScale(4, BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
            //16 本金
            sb.append(principalAmount.setScale(4, BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
            //17 利息
            sb.append(interestAmount.setScale(4, BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
            //18 手续费
            sb.append(feeAmount.setScale(4, BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
            //19 还款管理费
            sb.append("0.0000" + ReportingConstant.separator_union);
            //20 提前还款手续费
            sb.append(prepayFee.setScale(4, BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
            //21 还款手续费
            sb.append("0.0000" + ReportingConstant.separator_union);
            //22 罚息
            sb.append(penaltyAmount.setScale(4, BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
            //23 还款类型 EnumHandlerStatus 1:成功2:处理中3:失败
            if(ReportingConstant.PAYMENT_LOG_SUM_STATUS_S.equals(log.getSumStatus())){
                sb.append("1" + ReportingConstant.separator_union);
            }else if(ReportingConstant.PAYMENT_LOG_SUM_STATUS_F.equals(log.getSumStatus())){
                sb.append("3" + ReportingConstant.separator_union);
            }else{
                sb.append("2" + ReportingConstant.separator_union);
            }
            //24 优惠编号
            sb.append("" + ReportingConstant.separator_union);
            //25 交易时间
            String launchTime = DateUtils.format(log.getLaunchTime(),DateUtils.DATE_PATTERN_ANOTHER);
            sb.append(launchTime + ReportingConstant.separator_union);
            //26 统一流水号
            sb.append(log.getId() + ReportingConstant.separator_union);
            //27 本金调整值
            sb.append("0.0000" + ReportingConstant.separator_union);
            //28 利息调整值
            sb.append("0.0000" + ReportingConstant.separator_union);
            //29 分期手续费调整值
            sb.append("0.0000" + ReportingConstant.separator_union);
            //30 账户管理费调整值
            sb.append("0.0000" + ReportingConstant.separator_union);
            //31 罚息调整值
            sb.append("0.0000" + ReportingConstant.separator_union);
            //32 创建时间
            String createTime = DateUtils.format(log.getCreateTime(),DateUtils.DATE_PATTERN_ANOTHER);
            sb.append(createTime + ReportingConstant.separator_union);
            //33 更新时间
            sb.append("" + ReportingConstant.separator_union);
            //34 源系统标识
            SystemParameterRes sourceRes = systemParameterService.findByParamCode(ReportingConstant.SYS_SOURCE_ID,amLoanMainInfo.getTenantId());
            sb.append(sourceRes.getParamValue() + ReportingConstant.separator_union);
            //35 交易日期
            String businessDate = DateUtils.format(log.getBusinessDate(),DateUtils.DATE_PATTERN_ANOTHER);
            sb.append(businessDate + ReportingConstant.separator_union);
            //36 核心记账日期
            sb.append(businessDate + ReportingConstant.separator_union);
            //37 业务办理机构
            SystemParameterRes orgRes = systemParameterService.findByParamCode(ReportingConstant.SYS_ORGNO,amLoanMainInfo.getTenantId());
            sb.append(orgRes.getParamValue() + ReportingConstant.separator_union);
            //38 贷款分户账号
            sb.append("" + ReportingConstant.separator_union);
            //39 信贷合同号
            sb.append(subLoanId(tlPaymentMapping.getLoanId(),tlPaymentMapping.getTenantId()) + ReportingConstant.separator_union);
            //40 核心客户编号
            sb.append((customer.getFirstLevel().getEcifId() == null ? "":customer.getFirstLevel().getEcifId()) + ReportingConstant.separator_union);
            //41 明细科目编号
            SystemParameterRes repayAclgNo = systemParameterService.findByParamCode(ReportingConstant.SYS_REPAY_ACLG_NO,amLoanMainInfo.getTenantId());
            sb.append(repayAclgNo.getParamValue() + ReportingConstant.separator_union);
            //42 账户名称
            sb.append("" + ReportingConstant.separator_union);
            //43 交易类型 10--贷款回收
            sb.append("10" + ReportingConstant.separator_union);
            //44 交易借贷标志 D-借
            sb.append("D" + ReportingConstant.separator_union);
            //45 交易金额
            sb.append(totalAmount.setScale(4, BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
            //46 账户余额 可用额度
            //查询产品对应额度节点
            String limitId = creditLimitMappingService.getLimitId(log.getOrganizationId(),log.getChannel(),log.getProductId(),log.getTenantId());
            String useMode = creditLimitTypeService.getUserModal(limitId,log.getOrganizationId(),log.getTenantId());
            CmCustomerLimitInfo cmCustomerLimitInfo = null;
            if(ReportingConstant.USE_MODE_0.equals(useMode)){
                cmCustomerLimitInfo = extCmCustomerLimitInfoMapper.selectByTenIdAndCusIdAndLimitId(log.getTenantId(),log.getCustomerId(),limitId);
            }else{
                cmCustomerLimitInfo = extCmCustomerLimitInfoMapper.selectCustomerLimitInfo(log.getCustomerId(),log.getOrganizationId(),limitId,amLoanMainInfo.getContractNumber(),log.getTenantId());
            }
            if(null == cmCustomerLimitInfo){
                sb.append(BigDecimal.ZERO.setScale(4, BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
            }else{
                sb.append(cmCustomerLimitInfo.getLimitAvailable().setScale(4, BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
            }
            //47 对方账号 TODO
            SystemParameterRes acctNo = systemParameterService.findByParamCode(ReportingConstant.SYS_OPPT_ACCT_NO,amLoanMainInfo.getTenantId());
            sb.append(acctNo.getParamValue() + ReportingConstant.separator_union);
            //48 对方户名 TODO
            SystemParameterRes acctName = systemParameterService.findByParamCode(ReportingConstant.SYS_OPPT_ACCT_NAME,amLoanMainInfo.getTenantId());
            sb.append(acctName.getParamValue() + ReportingConstant.separator_union);
            //49 对方行号 TODO
            SystemParameterRes bankNo = systemParameterService.findByParamCode(ReportingConstant.SYS_OPPT_BANK_NO,amLoanMainInfo.getTenantId());
            sb.append(bankNo.getParamValue() + ReportingConstant.separator_union);
            //50 对方行名 TODO
            SystemParameterRes bankName = systemParameterService.findByParamCode(ReportingConstant.SYS_OPPT_BANK_NAME,amLoanMainInfo.getTenantId());
            sb.append(bankName.getParamValue() + ReportingConstant.separator_union);
            //51 交易渠道
            sb.append("11" + ReportingConstant.separator_union);
            //52 币种
            sb.append("CNY" + ReportingConstant.separator_union);
            //53 交易柜员号
            SystemParameterRes custMgNo = systemParameterService.findByParamCode(ReportingConstant.SYS_CUST_MG_NO,amLoanMainInfo.getTenantId());
            sb.append(custMgNo.getParamValue() + ReportingConstant.separator_union);
            //54 授权柜员号
            sb.append(custMgNo.getParamValue() + ReportingConstant.separator_union);
            //55 现转标志 2 转账
            sb.append("2" + ReportingConstant.separator_union);
            //56 贷款发放类别
            sb.append("D01" + ReportingConstant.separator_union);
            //57 贷款收回类别
            sb.append("E01" + ReportingConstant.separator_union);
            //58 冲补抹标志
            sb.append("1" + ReportingConstant.separator_union);
            //59 交易码
            sb.append("20000" + ReportingConstant.separator_union);
            //60 交易描述
            sb.append("还款交易");

            messageList.add(sb.toString());
        }
        return messageList;
    }

    @Override
    public String createThirdRepayFileMessage(TlThirdPartyPayment log) throws TxnException {
        StringBuffer sb = new StringBuffer();
        //获取贷款账户信息
        AmLoanAccountInfo amLoanAccountInfo = extAmLoanAccountInfoMapper.selectByLoanId(log.getLoanId(),log.getCustomerId(),log.getTenantId());
        //获取借据信息
        AmLoanMainInfo amLoanMainInfo = extAmLoanMainInfoMapper.selectByLoanIdAndCusId(log.getLoanId(),log.getCustomerId(),log.getTenantId());
        //获取对应期次还款计划
        AmRepaymentPlanInfo castPlan = extAmRepaymentPlanInfoMapper.selectByLoanIdAndBillingTenor(amLoanAccountInfo.getLoanId(),
                amLoanAccountInfo.getCustomerId(),amLoanAccountInfo.getTenantId(),amLoanAccountInfo.getCastTenor(),
                Arrays.asList(TransBizConstant.LOAN_PLAN_STATUS_0,TransBizConstant.LOAN_PLAN_STATUS_1, TransBizConstant.LOAN_PLAN_STATUS_2,
                        TransBizConstant.LOAN_PLAN_STATUS_7,TransBizConstant.LOAN_PLAN_STATUS_8,TransBizConstant.LOAN_PLAN_STATUS_6));
        //查询客户信息
        CustomerRes customer = customerService.getCustomerByChannelAndCustomerIdAndTensnId(log.getChannel(),
                log.getCustomerId(),log.getTenantId());

        //查询还款分配流水表
        List<TlPaymentAllocationLog> tlPaymentAllocationLogList = extTlPaymentAllocationLogMapper.findCustLog(log.getLoanId(),
                log.getSeqNo(),log.getCustomerId(),log.getTenantId());

        String detailId = null;
        tlPaymentAllocationLogList.sort(Comparator.comparing(TlPaymentAllocationLog::getId));
        for (TlPaymentAllocationLog tllog : tlPaymentAllocationLogList) {
            if (!tllog.getAccountType().equals("08")) {
                detailId = tllog.getAccountId();
                break;
            }
        }
        //1 租户号
        sb.append(amLoanAccountInfo.getTenantId() + ReportingConstant.separator_union);
        //2 明细号 原系统TXA_NUMBER
        sb.append(detailId + ReportingConstant.separator_union);
        //3 业务流水
        sb.append("" + ReportingConstant.separator_union);
        //4 合并流水
        sb.append("" + ReportingConstant.separator_union);
        //5 借据号
        sb.append(subLoanId(log.getLoanId(),log.getTenantId()) + ReportingConstant.separator_union);
        //6 用户编号
        sb.append(handleCustomerId(log.getCustomerId(),log.getTenantId()) + ReportingConstant.separator_union);
        //7 用户姓名
        sb.append(customer.getFirstLevel().getChineseName() + ReportingConstant.separator_union);
        //8 还款期次（1,2,3格式）
        for(TlPaymentAllocationLog tlPaymentAllocationLog : tlPaymentAllocationLogList){
            if(!tlPaymentAllocationLog.getAccountType().equals("08")){
                sb.append(tlPaymentAllocationLog.getBillingTenor() + ReportingConstant.separator_union);
                break ;
            }
        }

        //9 还款类型 EnumLineType 1:线上2:线下;
        sb.append("1" + ReportingConstant.separator_union);
        //10 是否统还 0 否 1 是
        String format = DateUtils.format(castPlan.getPaymentDueDate());
        String format1 = DateUtils.format(log.getBusinessDate());
        if(format.substring(format.length()-2).equals(format1.substring(format1.length()-2))){
            sb.append("0" + ReportingConstant.separator_union);
        }else{
            sb.append("1" + ReportingConstant.separator_union);
        }
        //11 还款操作类型
        if(ReportingConstant.REPAYMENT_TYPE_OVERDUE.equals(log.getPaymentType()) ||
                ReportingConstant.REPAYMENT_TYPE_BILLOVERDUEPAY.equals(log.getPaymentType())){
            //1 逾期还款
            sb.append("1" + ReportingConstant.separator_union);
        }else if(ReportingConstant.REPAYMENT_TYPE_PAY.equals(log.getPaymentType())){
            //2 正常还款
            sb.append("2" + ReportingConstant.separator_union);
        }else if(ReportingConstant.REPAYMENT_TYPE_PREPAY.equals(log.getPaymentType())||
                ReportingConstant.REPAYMENT_TYPE_PREPAY_CURR.equals(log.getPaymentType())){
            //3 提前还款
            sb.append("3" + ReportingConstant.separator_union);
        }else if(ReportingConstant.REPAYMENT_TYPE_CMPS.equals(log.getPaymentType())){
            //4 代偿还款
            sb.append("4" + ReportingConstant.separator_union);
        }else {
            sb.append("2" + ReportingConstant.separator_union);
        }
        //12 合作商编号
        sb.append("" + ReportingConstant.separator_union);
        //13 商户号
        sb.append("" + ReportingConstant.separator_union);
        //14 代偿人用户编号
        sb.append("" + ReportingConstant.separator_union);
        //区分成功，处理中
        BigDecimal totalAmount = BigDecimal.ZERO;//总金额
        BigDecimal principalAmount=BigDecimal.ZERO;//本金
        BigDecimal interestAmount=BigDecimal.ZERO;//利息
        BigDecimal penaltyAmount=BigDecimal.ZERO;//罚息
        BigDecimal feeAmount=BigDecimal.ZERO;//费用
        BigDecimal prepayFee=BigDecimal.ZERO;//提前还款手续费
        BigDecimal compountAmount = BigDecimal.ZERO;//复利

        //直接拿09交易账户金额
        for(TlPaymentAllocationLog allocationLog : tlPaymentAllocationLogList){
            if(ReportingConstant.ACCOUNT_TYPE_06.equals(allocationLog.getConnectAccountType())){
                principalAmount = principalAmount.add(allocationLog.getPostingAmount());
            }
            if(ReportingConstant.ACCOUNT_TYPE_04.equals(allocationLog.getConnectAccountType())){
                interestAmount = interestAmount.add(allocationLog.getPostingAmount());
            }
            if(ReportingConstant.ACCOUNT_TYPE_11.equals(allocationLog.getConnectAccountType())){
                penaltyAmount = penaltyAmount.add(allocationLog.getPostingAmount());
            }
            if(ReportingConstant.ACCOUNT_TYPE_12.equals(allocationLog.getConnectAccountType())){
                compountAmount = compountAmount.add(allocationLog.getPostingAmount());
            }

            //费用计算
            if(allocationLog.getTxnCode().substring(3,4).equals("2")){
                switch (allocationLog.getTxnCode().substring(5,6)){
                    case "1"://一次性手续费
                        feeAmount = feeAmount.add(allocationLog.getPostingAmount());
                        break;
                    case "2"://分期手续费
                        feeAmount = feeAmount.add(allocationLog.getPostingAmount());
                        break;
                    case "3"://提前还款手续费还款
                        feeAmount = feeAmount.add(allocationLog.getPostingAmount());
                        break;
                    case "4"://提前结清手续费还款
                        prepayFee = prepayFee.add(allocationLog.getPostingAmount());
                        break;
                }
            }
        }

        totalAmount = principalAmount.add(interestAmount).add(penaltyAmount).add(feeAmount).add(prepayFee).add(compountAmount);
        //15 还款总金额
        sb.append(totalAmount.setScale(4, BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
        //16 本金
        sb.append(principalAmount.setScale(4, BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
        //17 利息
        sb.append(interestAmount.setScale(4, BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
        //18 手续费
        sb.append(feeAmount.setScale(4, BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
        //19 还款管理费
        sb.append("0.0000" + ReportingConstant.separator_union);
        //20 提前还款手续费
        sb.append(prepayFee.setScale(4, BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
        //21 还款手续费
        sb.append("0.0000" + ReportingConstant.separator_union);
        //22 罚息
        sb.append(penaltyAmount.setScale(4, BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
        //23 还款类型 EnumHandlerStatus 1:成功2:处理中3:失败
        if(ReportingConstant.PAYMENT_LOG_SUM_STATUS_S.equals(log.getSumStatus())){
            sb.append("1" + ReportingConstant.separator_union);
        }else if(ReportingConstant.PAYMENT_LOG_SUM_STATUS_F.equals(log.getSumStatus())){
            sb.append("3" + ReportingConstant.separator_union);
        }else{
            sb.append("2" + ReportingConstant.separator_union);
        }
        //24 优惠编号
        sb.append("" + ReportingConstant.separator_union);
        //25 交易时间
        String launchTime = DateUtils.format(log.getBusinessDate(),DateUtils.DATE_PATTERN_ANOTHER);
        sb.append(launchTime + ReportingConstant.separator_union);
        //26 统一流水号
        sb.append(log.getId() + ReportingConstant.separator_union);
        //27 本金调整值
        sb.append("0.0000" + ReportingConstant.separator_union);
        //28 利息调整值
        sb.append("0.0000" + ReportingConstant.separator_union);
        //29 分期手续费调整值
        sb.append("0.0000" + ReportingConstant.separator_union);
        //30 账户管理费调整值
        sb.append("0.0000" + ReportingConstant.separator_union);
        //31 罚息调整值
        sb.append("0.0000" + ReportingConstant.separator_union);
        //32 创建时间
        String createTime = DateUtils.format(log.getCreateTime(),DateUtils.DATE_PATTERN_ANOTHER);
        sb.append(createTime + ReportingConstant.separator_union);
        //33 更新时间
        sb.append("" + ReportingConstant.separator_union);
        //34 源系统标识
        SystemParameterRes sourceRes = systemParameterService.findByParamCode(ReportingConstant.SYS_SOURCE_ID,amLoanMainInfo.getTenantId());
        sb.append(sourceRes.getParamValue() + ReportingConstant.separator_union);
        //35 交易日期
        String businessDate = DateUtils.format(log.getBusinessDate(),DateUtils.DATE_PATTERN_ANOTHER);
        sb.append(businessDate + ReportingConstant.separator_union);
        //36 核心记账日期
        sb.append(businessDate + ReportingConstant.separator_union);
        //37 业务办理机构
        SystemParameterRes orgRes = systemParameterService.findByParamCode(ReportingConstant.SYS_ORGNO,amLoanMainInfo.getTenantId());
        sb.append(orgRes.getParamValue() + ReportingConstant.separator_union);
        //38 贷款分户账号
        sb.append("" + ReportingConstant.separator_union);
        //39 信贷合同号
        sb.append(subLoanId(log.getLoanId(),log.getTenantId()) + ReportingConstant.separator_union);
        //40 核心客户编号
        sb.append((customer.getFirstLevel().getEcifId() == null ? "":customer.getFirstLevel().getEcifId()) + ReportingConstant.separator_union);
        //41 明细科目编号
        SystemParameterRes repayAclgNo = systemParameterService.findByParamCode(ReportingConstant.SYS_REPAY_ACLG_NO,amLoanMainInfo.getTenantId());
        sb.append(repayAclgNo.getParamValue() + ReportingConstant.separator_union);
        //42 账户名称
        sb.append("" + ReportingConstant.separator_union);
        //43 交易类型 10--贷款回收
        sb.append("10" + ReportingConstant.separator_union);
        //44 交易借贷标志 D-借
        sb.append("D" + ReportingConstant.separator_union);
        //45 交易金额
        sb.append(totalAmount.setScale(4, BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
        //46 账户余额 可用额度
        //查询产品对应额度节点
        String limitId = creditLimitMappingService.getLimitId(log.getOrganizationId(),log.getChannel(),log.getProductId(),log.getTenantId());
        String useMode = creditLimitTypeService.getUserModal(limitId,log.getOrganizationId(),log.getTenantId());
        CmCustomerLimitInfo cmCustomerLimitInfo = null;
        if(ReportingConstant.USE_MODE_0.equals(useMode)){
            cmCustomerLimitInfo = extCmCustomerLimitInfoMapper.selectByTenIdAndCusIdAndLimitId(log.getTenantId(),log.getCustomerId(),limitId);
        }else{
            cmCustomerLimitInfo = extCmCustomerLimitInfoMapper.selectCustomerLimitInfo(log.getCustomerId(),log.getOrganizationId(),limitId,amLoanMainInfo.getContractNumber(),log.getTenantId());
        }
        if(null == cmCustomerLimitInfo){
            sb.append(BigDecimal.ZERO.setScale(4, BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
        }else{
            sb.append(cmCustomerLimitInfo.getLimitAvailable().setScale(4, BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
        }
        //47 对方账号 TODO
        SystemParameterRes acctNo = systemParameterService.findByParamCode(ReportingConstant.SYS_OPPT_ACCT_NO,amLoanMainInfo.getTenantId());
        sb.append(acctNo.getParamValue() + ReportingConstant.separator_union);
        //48 对方户名 TODO
        SystemParameterRes acctName = systemParameterService.findByParamCode(ReportingConstant.SYS_OPPT_ACCT_NAME,amLoanMainInfo.getTenantId());
        sb.append(acctName.getParamValue() + ReportingConstant.separator_union);
        //49 对方行号 TODO
        SystemParameterRes bankNo = systemParameterService.findByParamCode(ReportingConstant.SYS_OPPT_BANK_NO,amLoanMainInfo.getTenantId());
        sb.append(bankNo.getParamValue() + ReportingConstant.separator_union);
        //50 对方行名 TODO
        SystemParameterRes bankName = systemParameterService.findByParamCode(ReportingConstant.SYS_OPPT_BANK_NAME,amLoanMainInfo.getTenantId());
        sb.append(bankName.getParamValue() + ReportingConstant.separator_union);
        //51 交易渠道
        sb.append("11" + ReportingConstant.separator_union);
        //52 币种
        sb.append("CNY" + ReportingConstant.separator_union);
        //53 交易柜员号
        SystemParameterRes custMgNo = systemParameterService.findByParamCode(ReportingConstant.SYS_CUST_MG_NO,amLoanMainInfo.getTenantId());
        sb.append(custMgNo.getParamValue() + ReportingConstant.separator_union);
        //54 授权柜员号
        sb.append(custMgNo.getParamValue() + ReportingConstant.separator_union);
        //55 现转标志 2 转账
        sb.append("2" + ReportingConstant.separator_union);
        //56 贷款发放类别
        sb.append("D01" + ReportingConstant.separator_union);
        //57 贷款收回类别
        sb.append("E01" + ReportingConstant.separator_union);
        //58 冲补抹标志
        sb.append("1" + ReportingConstant.separator_union);
        //59 交易码
        sb.append("20000" + ReportingConstant.separator_union);
        //60 交易描述
        sb.append("还款交易");

        return sb.toString();
    }

    @Override
    public String createLoanInfoFileMessage(AmLoanAccountInfo amLoanAccountInfo) throws TxnException {
        StringBuffer sb = new StringBuffer();

        //查询产品信息
        PrProductTable productTable = productTableService.findProByProIdAndOrgId(amLoanAccountInfo.getProductId(), amLoanAccountInfo.getOrganizationId(), amLoanAccountInfo.getTenantId());
        //查询贷款信息表
        AmLoanMainInfo amLoanMainInfo = extAmLoanMainInfoMapper.selectByLoanIdAndCusId(amLoanAccountInfo.getLoanId(), amLoanAccountInfo.getCustomerId(), amLoanAccountInfo.getTenantId());
        //获取客户默认扣款卡
        CmCustomerBankcardInfo bankcardInfo = bankCardService.getBankCardByCustomerId(amLoanAccountInfo.getCustomerId(), "Y",
                amLoanAccountInfo.getChannel(), amLoanAccountInfo.getTenantId());

        //查询客户放款流水
        List<TlDisbursementLog> tlDisbursementLogList = extTlDisbursementLogMapper.selectBySumStatusAndLoanId(amLoanMainInfo.getLoanId(),amLoanMainInfo.getCustomerId(),amLoanMainInfo.getTenantId(),
                ReportingConstant.DISBURSEMENT_LOG_SUM_STATUS_S);

        //查询客户信息
        CustomerRes customer = customerService.getCustomerByChannelAndCustomerIdAndTensnId(amLoanMainInfo.getChannel(),
                amLoanMainInfo.getCustomerId(), amLoanMainInfo.getTenantId());
        //机构信息
        PrOrganizationTable org = organizationTableService.findByOrId(amLoanAccountInfo.getOrganizationId(), amLoanAccountInfo.getTenantId());
        //查询下期还款计划
        AmRepaymentPlanInfo amRepaymentPlanInfo = extAmRepaymentPlanInfoMapper.selectByLoanIdAndBillingTenor(amLoanMainInfo.getLoanId(), amLoanMainInfo.getCustomerId(),
                amLoanMainInfo.getTenantId(), amLoanAccountInfo.getCastTenor(),
                Arrays.asList(TransBizConstant.LOAN_PLAN_STATUS_0, TransBizConstant.LOAN_PLAN_STATUS_1, TransBizConstant.LOAN_PLAN_STATUS_2,
                        TransBizConstant.LOAN_PLAN_STATUS_7, TransBizConstant.LOAN_PLAN_STATUS_8, TransBizConstant.LOAN_PLAN_STATUS_6));
        //查询最早一期延滞交易账户
        AmDelinquencyInfo amDelinquencyInfo = extAmDelinquencyInfoMapper.getMinDelqByStatus(amLoanMainInfo.getLoanId(),amLoanMainInfo.getCustomerId(),amLoanMainInfo.getTenantId(),TransBizConstant.ACCOUNT_STATUS_1);

        DecimalFormat df2 = new DecimalFormat("0.000000");

        //1 租户号
        sb.append(amLoanAccountInfo.getTenantId() + ReportingConstant.separator_union);
        //2 借据号
        sb.append(subLoanId(amLoanAccountInfo.getLoanId(),amLoanAccountInfo.getTenantId()) + ReportingConstant.separator_union);
        //3 授信id 客户号+X004
        sb.append((handleCustomerId(amLoanAccountInfo.getCustomerId(),amLoanAccountInfo.getTenantId()) + "X004") + ReportingConstant.separator_union);
        //4 产品编号
        if(ReportingConstant.UNION_DEFAULT_TENANT_ID.equals(amLoanAccountInfo.getTenantId())){
            SystemParameterRes proRes = systemParameterService.findByParamCode(ReportingConstant.SYS_PRODUCT_ID,amLoanAccountInfo.getTenantId());
            sb.append(proRes.getParamValue() + ReportingConstant.separator_union);
        }else{
            sb.append(productTable.getProductId() + ReportingConstant.separator_union);
        }
        //5 产品名称
        sb.append(productTable.getChineseName() + ReportingConstant.separator_union);
        //6 产品主键
        sb.append(productTable.getId() + ReportingConstant.separator_union);
        //7 商品类型
        sb.append("" + ReportingConstant.separator_union);
        //8 借款码 主键
        sb.append(amLoanAccountInfo.getId() + ReportingConstant.separator_union);
        //9 合同号
        sb.append(subLoanId(amLoanMainInfo.getLoanId(),amLoanMainInfo.getTenantId()) + ReportingConstant.separator_union);
        //10 托管类型 1 非托管
        sb.append("1" + ReportingConstant.separator_union);
        //11 借款人编号
        sb.append(handleCustomerId(amLoanAccountInfo.getCustomerId(),amLoanAccountInfo.getTenantId()) + ReportingConstant.separator_union);
        //12 借款人类型 200 个人客户
        sb.append("200" + ReportingConstant.separator_union);
        //13 商户号
        SystemParameterRes custMgNo = systemParameterService.findByParamCode(ReportingConstant.SYS_CUST_MG_NO,amLoanMainInfo.getTenantId());
        sb.append(custMgNo.getParamValue() + ReportingConstant.separator_union);
        //14 门店Id
        sb.append("" + ReportingConstant.separator_union);
        //15 合作方用户编号
        sb.append("" + ReportingConstant.separator_union);
        //16 合作方费用
        sb.append("0" + ReportingConstant.separator_union);
        //17 剩余本金
        sb.append(amLoanAccountInfo.getRemainPrincipal() + ReportingConstant.separator_union);
        //18 处理中的本金
        sb.append("0" + ReportingConstant.separator_union);
        //19 支用金额
        sb.append(amLoanMainInfo.getLoanAmount() + ReportingConstant.separator_union);
        //20 借据状态 1:正常2:逾期3:结清
        if (ReportingConstant.ACCOUNT_STATUS_2.equals(amLoanAccountInfo.getAccountStatus())) {
            sb.append("2" + ReportingConstant.separator_union);
        } else if (ReportingConstant.ACCOUNT_STATUS_7.equals(amLoanAccountInfo.getAccountStatus()) ||
                ReportingConstant.ACCOUNT_STATUS_8.equals(amLoanAccountInfo.getAccountStatus())) {
            sb.append("5" + ReportingConstant.separator_union);
        } else {
            sb.append("1" + ReportingConstant.separator_union);
        }
        //21 提前到期状态 结清状态为 1 其他为 0
        if (ReportingConstant.ACCOUNT_STATUS_7.equals(amLoanAccountInfo.getAccountStatus())) {
            sb.append("1" + ReportingConstant.separator_union);
        } else {
            sb.append("0" + ReportingConstant.separator_union);
        }
        //22 是否支持代扣
        sb.append("1" + ReportingConstant.separator_union);
        //23 代扣签约时间
        String createTime = DateUtils.format(amLoanMainInfo.getTxnTime(), "yyyyMMdd HH:mm:ss");
        sb.append(createTime + ReportingConstant.separator_union);
        //24 代扣账号
        if (null == bankcardInfo) {
            sb.append("" + ReportingConstant.separator_union);
        } else {
            sb.append(bankcardInfo.getCardNumber() + ReportingConstant.separator_union);
        }
        //25 代扣用户姓名
        sb.append(customer.getFirstLevel().getChineseName() + ReportingConstant.separator_union);
        //26 代扣用户编号
        sb.append(handleCustomerId(amLoanAccountInfo.getCustomerId(),amLoanAccountInfo.getTenantId()) + ReportingConstant.separator_union);
        //27 代扣账号类型
        sb.append("" + ReportingConstant.separator_union);
        //28 证件类型 手机号
        sb.append(customer.getSecondLevel().getMobile() + ReportingConstant.separator_union);
        //29 证件号
        sb.append(customer.getFirstLevel().getIdNumber() + ReportingConstant.separator_union);
        //30 证件类型 10 核对证件
        sb.append("10" + ReportingConstant.separator_union);
        //31 总期次
        sb.append(amLoanMainInfo.getTotalTenor() + ReportingConstant.separator_union);
        //32 初始利率 直接取年利率精度问题
        sb.append(df2.format(amLoanMainInfo.getInterestRate().multiply(new BigDecimal(100))) + ReportingConstant.separator_union);
        //33 执行利率
        sb.append(df2.format(amLoanMainInfo.getInterestRate().multiply(new BigDecimal(100))) + ReportingConstant.separator_union);
        //34 起息日
        String intrStart = DateUtils.format(amLoanMainInfo.getInterestStartDate(), DateUtils.DATE_PATTERN_ANOTHER);
        sb.append(intrStart + ReportingConstant.separator_union);
        //35 结清日
        String lastDate = DateUtils.format(amLoanMainInfo.getLastPaymentDate(), DateUtils.DATE_PATTERN_ANOTHER);
        sb.append(lastDate + ReportingConstant.separator_union);
        //36 真正结清日
        sb.append((amLoanAccountInfo.getPayoffDate() == null ? "" : DateUtils.format(amLoanAccountInfo.getPayoffDate(), DateUtils.DATE_PATTERN_ANOTHER)) + ReportingConstant.separator_union);
        //37 核销状态 EnumVerificationStatus 0-正常 1-核销
        sb.append(amLoanAccountInfo.getChargeoffFlag() + ReportingConstant.separator_union);
        //38 核销时间
        sb.append((amLoanAccountInfo.getChargeoffDate() == null ? "" : DateUtils.format(amLoanAccountInfo.getChargeoffDate(), DateUtils.DATE_PATTERN_ANOTHER)) + ReportingConstant.separator_union);
        //39 期限 起息日和结清日的差
        int days = DateUtils.getDaysBetween(amLoanMainInfo.getLastPaymentDate(), amLoanMainInfo.getInterestStartDate());
        sb.append(days + ReportingConstant.separator_union);
        //40 优惠编号
        sb.append("" + ReportingConstant.separator_union);
        //41 费用规则编号
        sb.append("" + ReportingConstant.separator_union);
        //42 是否支持代扣
        sb.append("1" + ReportingConstant.separator_union);
        //43 放款流水
        sb.append(amLoanMainInfo.getSerialNumber() + ReportingConstant.separator_union);
        //44 摘要
        sb.append("" + ReportingConstant.separator_union);
        //45 机构号
        SystemParameterRes orgNo = systemParameterService.findByParamCode(ReportingConstant.SYS_ORGNO,amLoanMainInfo.getTenantId());
        sb.append(orgNo.getParamValue() + ReportingConstant.separator_union);
        //46 支付方式 10 -自主支付 20 -受托支付 30 -混合支付
        if(ReportingConstant.UNION_DEFAULT_TENANT_ID.equals(amLoanMainInfo.getTenantId())){
            sb.append("10" + ReportingConstant.separator_union);
        }else{
            if(CollectionUtils.isEmpty(tlDisbursementLogList) || ReportingConstant.NO_FLAG.equals(tlDisbursementLogList.get(0).getEntrustedPayment())){
                sb.append("10" + ReportingConstant.separator_union);
            }else{
                sb.append("20" + ReportingConstant.separator_union);
            }
        }
        //47 渠道编号
        sb.append("" + ReportingConstant.separator_union);
        //48 创建时间
        sb.append(createTime + ReportingConstant.separator_union);
        //49 更新时间
        sb.append("" + ReportingConstant.separator_union);
        //50 核心记账日期
        sb.append((DateUtils.format(amLoanMainInfo.getPostingDate(), DateUtils.DATE_PATTERN_ANOTHER)) + ReportingConstant.separator_union);
        //51 交易日期
        sb.append((DateUtils.format(amLoanMainInfo.getTxnTime(), DateUtils.DATE_PATTERN_ANOTHER)) + ReportingConstant.separator_union);
        //52 业务办理机构
        sb.append(orgNo.getParamValue() + ReportingConstant.separator_union);
        //53 贷款分户账号
        sb.append(bankcardInfo.getCardNumber() + ReportingConstant.separator_union);
        //54 核心客户编号
        sb.append(customer.getFirstLevel().getEcifId() + ReportingConstant.separator_union);
        //55 科目编号
        SystemParameterRes aclgRes = null;
        if(ReportingConstant.UNION_DEFAULT_TENANT_ID.equals(amLoanMainInfo.getTenantId())){
            //根据订单状态判断科目
            if(ReportingConstant.ACCOUNT_STATUS_1.equals(amLoanAccountInfo.getAccountStatus())){
                aclgRes = systemParameterService.findByParamCode(ReportingConstant.TA_SYS_ACLG_NO,amLoanMainInfo.getTenantId());
            }else if(ReportingConstant.ACCOUNT_STATUS_2.equals(amLoanAccountInfo.getAccountStatus())&&
                    ReportingConstant.NON_ACCRUALS_FLAG_0.equals(amLoanAccountInfo.getNonAccrualsFlag())){
                aclgRes = systemParameterService.findByParamCode(ReportingConstant.TA_SYS_ACLG_NO_59201,amLoanMainInfo.getTenantId());
            }else if(ReportingConstant.ACCOUNT_STATUS_2.equals(amLoanAccountInfo.getAccountStatus())&&
                    ReportingConstant.NON_ACCRUALS_FLAG_1.equals(amLoanAccountInfo.getNonAccrualsFlag())){
                aclgRes = systemParameterService.findByParamCode(ReportingConstant.TA_SYS_ACLG_NO_59301,amLoanMainInfo.getTenantId());
            }
        }else if(ReportingConstant.UNION_LS_TENANT_ID.equals(amLoanMainInfo.getTenantId())){
            //需要区分经营 消费贷
            if(amLoanMainInfo.getLoanType().equals(ReportingConstant.LOAN_TYPE_6)){
                if(ReportingConstant.ACCOUNT_STATUS_1.equals(amLoanAccountInfo.getAccountStatus())){
                    aclgRes = systemParameterService.findByParamCode(ReportingConstant.LS_SYS_ACLG_NO_JY,amLoanMainInfo.getTenantId());
                }else if(ReportingConstant.ACCOUNT_STATUS_2.equals(amLoanAccountInfo.getAccountStatus())&&
                        ReportingConstant.NON_ACCRUALS_FLAG_0.equals(amLoanAccountInfo.getNonAccrualsFlag())){
                    aclgRes = systemParameterService.findByParamCode(ReportingConstant.LS_SYS_ACLG_NO_59201_JY,amLoanMainInfo.getTenantId());
                }else if(ReportingConstant.ACCOUNT_STATUS_2.equals(amLoanAccountInfo.getAccountStatus())&&
                        ReportingConstant.NON_ACCRUALS_FLAG_1.equals(amLoanAccountInfo.getNonAccrualsFlag())){
                    aclgRes = systemParameterService.findByParamCode(ReportingConstant.LS_SYS_ACLG_NO_59301_JY,amLoanMainInfo.getTenantId());
                }
            }else{
                if(ReportingConstant.ACCOUNT_STATUS_1.equals(amLoanAccountInfo.getAccountStatus())){
                    aclgRes = systemParameterService.findByParamCode(ReportingConstant.LS_SYS_ACLG_NO_XF,amLoanMainInfo.getTenantId());
                }else if(ReportingConstant.ACCOUNT_STATUS_2.equals(amLoanAccountInfo.getAccountStatus())&&
                        ReportingConstant.NON_ACCRUALS_FLAG_0.equals(amLoanAccountInfo.getNonAccrualsFlag())){
                    aclgRes = systemParameterService.findByParamCode(ReportingConstant.LS_SYS_ACLG_NO_59201_XF,amLoanMainInfo.getTenantId());
                }else if(ReportingConstant.ACCOUNT_STATUS_2.equals(amLoanAccountInfo.getAccountStatus())&&
                        ReportingConstant.NON_ACCRUALS_FLAG_1.equals(amLoanAccountInfo.getNonAccrualsFlag())){
                    aclgRes = systemParameterService.findByParamCode(ReportingConstant.LS_SYS_ACLG_NO_59301_XF,amLoanMainInfo.getTenantId());
                }
            }
        }
        if(null != aclgRes){
            sb.append(aclgRes.getParamValue() + ReportingConstant.separator_union);
        }else{
            sb.append("" + ReportingConstant.separator_union);
        }
        //56 科目名称
        SystemParameterRes aclgName = systemParameterService.findByParamCode(ReportingConstant.SYS_ACLG_NAME,amLoanMainInfo.getTenantId());
        sb.append(aclgName.getParamValue() + ReportingConstant.separator_union);
        //57 币种
        sb.append("CNY" + ReportingConstant.separator_union);

        BigDecimal overTotalAmt = BigDecimal.ZERO;//逾期总金额
        BigDecimal overPrincipalAmt = BigDecimal.ZERO;//逾期本金
        BigDecimal overInterest = BigDecimal.ZERO;//逾期利息 利息 + 罚息
        if (ReportingConstant.ACCOUNT_STATUS_2.equals(amLoanAccountInfo.getAccountStatus())) {
            //计算欠款
            DebtBean debtBean = debtCalculationService.getBalance(amLoanAccountInfo, org.getNextProcessingDate(), true, null, null, false);
            overTotalAmt =  debtBean.getTotalAmount();
            overPrincipalAmt = debtBean.getPrincipalAmount();
            overInterest = debtBean.getInterestAmount().add(debtBean.getPenaltyAmount());

        }
        //58 贷款逾期余额
        sb.append(overTotalAmt + ReportingConstant.separator_union);
        //59 欠本余额
        sb.append(overPrincipalAmt + ReportingConstant.separator_union);
        if(null != amDelinquencyInfo){
            //60 欠本天数
            sb.append(amDelinquencyInfo.getDelqDays() + ReportingConstant.separator_union);
        }else{
            //60 欠本天数
            sb.append("" + ReportingConstant.separator_union);
        }

        //61 欠息余额
        sb.append(overInterest + ReportingConstant.separator_union);

        if(null != amDelinquencyInfo){
            //62 欠息天数
            sb.append(amDelinquencyInfo.getDelqDays() + ReportingConstant.separator_union);
        }else{
            //62 欠息天数
            sb.append("" + ReportingConstant.separator_union);
        }
        //63 本期还款
        if (ReportingConstant.ACCOUNT_STATUS_7.equals(amLoanAccountInfo.getAccountStatus())) {

            BigDecimal principal= amLoanMainInfo.getLoanAmount();//本金

            BigDecimal interst = extAmInterestAccrualInfoMapper.sumInterAccrualInfo(amLoanAccountInfo.getLoanId(),amLoanAccountInfo.getCustomerId(),
                    amLoanAccountInfo.getTenantId());
            if(null != interst && interst.compareTo(BigDecimal.ZERO) > 0){
                principal = principal.add(interst);
            }

            sb.append(principal + ReportingConstant.separator_union);
        } else {
            int castTenor = amLoanAccountInfo.getCastTenor();
            //判断处理日期是否是还款日
            String busiDate = DateUtils.formatDate(org.getToday(),DateUtils.DATE_PATTERN);
            if(busiDate.substring(8,10).equals(amLoanMainInfo.getPaymentDateDd())){
                castTenor = castTenor - 1;
            }

            TlPaymentAllocationLog tlPaymentAllocationLog = new TlPaymentAllocationLog();
            tlPaymentAllocationLog.setBillingTenor(castTenor);
            tlPaymentAllocationLog.setLoanId(amLoanAccountInfo.getLoanId());
            tlPaymentAllocationLog.setCustomerId(amLoanAccountInfo.getCustomerId());
            tlPaymentAllocationLog.setTenantId(amLoanAccountInfo.getTenantId());

            List<TlPaymentAllocationLog> tlPaymentAllocationLogList = extTlPaymentAllocationLogMapper.selectListByCondition(tlPaymentAllocationLog);

            if(CollectionUtils.isNotEmpty(tlPaymentAllocationLogList)){
                BigDecimal payAmt = BigDecimal.ZERO;
                for(TlPaymentAllocationLog allLog : tlPaymentAllocationLogList){
                    payAmt = payAmt.add(allLog.getPostingAmount());
                }
                sb.append(payAmt + ReportingConstant.separator_union);
            }else{
                sb.append("0" + ReportingConstant.separator_union);
            }
        }
        //64 减值准备
        sb.append("0" + ReportingConstant.separator_union);
        //65 贷款期限
        int days2 = DateUtils.getDaysBetween(amLoanMainInfo.getLastPaymentDate(),amLoanMainInfo.getInterestStartDate());
        sb.append(days2 + ReportingConstant.separator_union);
        //66 展期次数
        sb.append("" + ReportingConstant.separator_union);
        //67 当前期数
        sb.append(amLoanAccountInfo.getCastTenor() + ReportingConstant.separator_union);
        //68 贷款实际发放日期 yyyyMMdd
        sb.append((DateUtils.format(amLoanMainInfo.getInterestStartDate(),DateUtils.DATE_PATTERN_ANOTHER)) + ReportingConstant.separator_union);
        //69 贷款原始到期日期
        sb.append((DateUtils.format(amLoanMainInfo.getLastPaymentDate(),DateUtils.DATE_PATTERN_ANOTHER)) + ReportingConstant.separator_union);
        //70 贷款实际到期日期
        sb.append((amLoanAccountInfo.getPayoffDate() == null ? "" :DateUtils.format(amLoanAccountInfo.getPayoffDate(),DateUtils.DATE_PATTERN_ANOTHER)) + ReportingConstant.separator_union);

        BigDecimal inInter = BigDecimal.ZERO;//表内利息
        BigDecimal outInter = BigDecimal.ZERO;//表外利息
        if(ReportingConstant.ACCOUNT_STATUS_2.equals(amLoanAccountInfo.getAccountStatus())){
            //查询逾期期数
            List<AmDelinquencyInfo> amDelinquencyInfoList = extAmDelinquencyInfoMapper.selectDelqInfoByLoanId(amLoanMainInfo.getLoanId(),amLoanMainInfo.getCustomerId(),amLoanMainInfo.getTenantId(),Arrays.asList(TransBizConstant.ACCOUNT_STATUS_1));
            List<Integer> billList = new ArrayList<>();
            for(AmDelinquencyInfo amDelinquencyInfo1 : amDelinquencyInfoList){
                billList.add(amDelinquencyInfo1.getBillingTenor());
            }

            //查询累计账户
            List<String> acctTypeList = new ArrayList<>();
            acctTypeList.add(ReportingConstant.INTEREST_ACCRUAL_TYPE_66);
            acctTypeList.add(ReportingConstant.INTEREST_ACCRUAL_TYPE_10);
            acctTypeList.add(ReportingConstant.INTEREST_ACCRUAL_TYPE_20);

            List<String> statusList = new ArrayList<>();
            statusList.add(ReportingConstant.ACCOUNT_STATUS_1);

            List<AmInterestAccrualInfo> amInterestAccrualInfoList = extAmInterestAccrualInfoMapper.selectByStatusAndType(amLoanMainInfo.getLoanId(),amLoanMainInfo.getCustomerId(),
                    amLoanMainInfo.getTenantId(),statusList,acctTypeList,billList);
            if(CollectionUtils.isNotEmpty(amInterestAccrualInfoList)){
                for(AmInterestAccrualInfo amInterestAccrualInfo : amInterestAccrualInfoList){
                    if(amInterestAccrualInfo.getNonAccrualsFlag().equals(ReportingConstant.NON_ACCRUALS_FLAG_0)){
                        //应计
                        inInter = inInter.add(amInterestAccrualInfo.getAccrualTotalAccruInterest());
                    }else{
                        outInter = outInter.add(amInterestAccrualInfo.getAccrualTotalAccruInterest());
                    }
                }
            }
            List<String> typeList = new ArrayList<>();
            typeList.add(ReportingConstant.ACCOUNT_TYPE_04);
            typeList.add(ReportingConstant.ACCOUNT_TYPE_11);
            typeList.add(ReportingConstant.ACCOUNT_TYPE_17);

            List<String> statusList2 = new ArrayList<>();
            statusList2.add(ReportingConstant.ACCOUNT_STATUS_2);
            //查询利息，罚息交易账户
            List<AmAccountMainInfo> amAccountMainInfoList = extAmAccountMainInfoMapper.selectAccounts(amLoanAccountInfo.getLoanId(),typeList,amLoanAccountInfo.getCustomerId(),
                    amLoanAccountInfo.getTenantId(),statusList2);
            if(CollectionUtils.isNotEmpty(amAccountMainInfoList)){
                for(AmAccountMainInfo amAccountMainInfo : amAccountMainInfoList){
                    if(amAccountMainInfo.getNonAccrualsFlag().equals(ReportingConstant.NON_ACCRUALS_FLAG_0)){
                        //应计
                        inInter = inInter.add(amAccountMainInfo.getPostingAmount().subtract(amAccountMainInfo.getRepayAmount()));
                    }else{
                        outInter = outInter.add(amAccountMainInfo.getPostingAmount().subtract(amAccountMainInfo.getRepayAmount()));
                    }
                }
            }

        }
        //71 表内欠息余额
        sb.append(inInter + ReportingConstant.separator_union);
        //72 表外欠息余额
        sb.append(outInter + ReportingConstant.separator_union);
        //73 逾期日期
        if(null != amDelinquencyInfo){
            sb.append((DateUtils.format(amDelinquencyInfo.getDelqDate(),DateUtils.DATE_PATTERN_ANOTHER)) + ReportingConstant.separator_union);
        }else{
            sb.append("" + ReportingConstant.separator_union);
        }
        //74 信贷产品类别
        if(ReportingConstant.UNION_DEFAULT_TENANT_ID.equals(amLoanAccountInfo.getTenantId())){
            sb.append("F021" + ReportingConstant.separator_union);
        }else{
            if(ReportingConstant.LOAN_TYPE_6.equals(productTable.getTableType())){
                sb.append("F022" + ReportingConstant.separator_union);
            }else{
                sb.append("F021" + ReportingConstant.separator_union);
            }
        }

        //75 贷款入账账号 扣款流水里的用户扣款卡号
        if(CollectionUtils.isNotEmpty(tlDisbursementLogList)){
            sb.append(tlDisbursementLogList.get(0).getPayeeAccount() + ReportingConstant.separator_union);
        }else{
            sb.append("" + ReportingConstant.separator_union);
        }
        //76 贷款五级分类
        sb.append(transFive(amLoanAccountInfo.getLoanClassify()) + ReportingConstant.separator_union);

        BigDecimal lastPayAmt = BigDecimal.ZERO;//最近还款金额
        String lastPayDate = "";//最近还款日期

        //获取最近一次的还款流水号 seq_no
        String paymenSeqno = getLastPaymentSeqNo(amLoanMainInfo.getLoanId(),amLoanMainInfo.getCustomerId(),amLoanMainInfo.getTenantId());

        if(StringUtils.isNotBlank(paymenSeqno)){
            List<TlPaymentAllocationLog> tlPaymentAllocationLogList = extTlPaymentAllocationLogMapper.selectBySeqNoAndTenantId(paymenSeqno,amLoanMainInfo.getTenantId());
            if(CollectionUtils.isNotEmpty(tlPaymentAllocationLogList)){
                lastPayDate = DateUtils.format(tlPaymentAllocationLogList.get(0).getPostingDate(),DateUtils.DATE_PATTERN_ANOTHER);

                for(TlPaymentAllocationLog log : tlPaymentAllocationLogList){
                    //只取最后一期的
                    if(lastPayDate.equals(DateUtils.format(log.getPostingDate(),DateUtils.DATE_PATTERN_ANOTHER))){
                        lastPayAmt = lastPayAmt.add(log.getPostingAmount());
                    }
                }
            }
        }

        //77 最近一次还款金额
        sb.append(lastPayAmt + ReportingConstant.separator_union);
        //78 最近一次还款日期
        sb.append(lastPayDate + ReportingConstant.separator_union);
        //79 执行利率 百分比不带百分号
        sb.append(df2.format(amLoanMainInfo.getInterestRate().multiply(new BigDecimal(100))) + ReportingConstant.separator_union);
        //80 利率类型 RF01 固定利率
        sb.append("RF01" + ReportingConstant.separator_union);
        //81 利率调整方式 00 固定调整方式(不调整)
        sb.append("00" + ReportingConstant.separator_union);
        //82 利率调整周期
        sb.append("" + ReportingConstant.separator_union);
        //83 基准利率 百分比不带百分号
        sb.append(df2.format(amLoanMainInfo.getInterestRate().multiply(new BigDecimal(100))) + ReportingConstant.separator_union);
        //84 利率浮动
        sb.append("0" + ReportingConstant.separator_union);

        String paymentMode="";
        switch (amLoanMainInfo.getAmortMethodTableId()){
            case ReportingConstant.PRIN_CHARGE_OPTION_EPI ://等额本息
                paymentMode="04";
                break;
            case ReportingConstant.PRIN_CHARGE_OPTION_MI_YP ://按月付息，按年还本
                paymentMode="03";
                break;
        }
        sb.append(paymentMode + ReportingConstant.separator_union);
        //86 还款周期 01 按月，
        sb.append("01" + ReportingConstant.separator_union);
        //87 还本频率 01 按月，
        sb.append("01" + ReportingConstant.separator_union);
        //88 还息频率 01 按月，
        sb.append("01" + ReportingConstant.separator_union);
        //89 还款账号
        sb.append(bankcardInfo.getCardNumber() + ReportingConstant.separator_union);
        //90 还款渠道 11 统一支付平台系统
        sb.append("11" + ReportingConstant.separator_union);
        //91 计息标志 1 记利息
        sb.append("1" + ReportingConstant.separator_union);
        //92 计息方式 2 逐笔计息法
        sb.append("2" + ReportingConstant.separator_union);
        //93 计息频率 98 不定期结息
        sb.append("98" + ReportingConstant.separator_union);
        //94 下次还款日期
        String nextPaymentDate = DateUtils.format(amLoanAccountInfo.getNextPaymentDate(),DateUtils.DATE_PATTERN_ANOTHER);
        sb.append(nextPaymentDate + ReportingConstant.separator_union);
        //95 下次还款金额
        BigDecimal nextPaymentAmt = BigDecimal.ZERO;
        if(null != amRepaymentPlanInfo){
            nextPaymentAmt = nextPaymentAmt.add(amRepaymentPlanInfo.getTotalAmount());
        }
        sb.append(nextPaymentAmt + ReportingConstant.separator_union);
        //96 信贷员姓名
        SystemParameterRes custMgName = systemParameterService.findByParamCode(ReportingConstant.SYS_CUST_MG_NAME,amLoanMainInfo.getTenantId());
        sb.append(custMgName.getParamValue() + ReportingConstant.separator_union);
        //97 信贷员员工号
        sb.append(custMgNo.getParamValue() + ReportingConstant.separator_union);
        //98 贷款发放类型 1-新增
        sb.append("1" + ReportingConstant.separator_union);
        //99 连续欠款期数
        sb.append("" + ReportingConstant.separator_union);
        //100 累计欠款期数
        sb.append("" + ReportingConstant.separator_union);
        //101 核销标志
        if(ReportingConstant.NO_FLAG.equals(amLoanAccountInfo.getChargeoffFlag())){
            sb.append("" + ReportingConstant.separator_union);
        }else{
            sb.append(amLoanAccountInfo.getChargeoffFlag() + ReportingConstant.separator_union);
        }
        //102 核销金额
        sb.append((amLoanAccountInfo.getChargeoffAmount()==null?"":amLoanAccountInfo.getChargeoffAmount()) + ReportingConstant.separator_union);
        //103 核销本金
        sb.append((amLoanAccountInfo.getChargeoffAmount()==null?"0":amLoanAccountInfo.getChargeoffAmount()) + ReportingConstant.separator_union);
        //104 核销表内利息
        sb.append(inInter + ReportingConstant.separator_union);
        //105 核销表外利息
        sb.append(outInter + ReportingConstant.separator_union);
        //106 核销日期
        sb.append((amLoanAccountInfo.getChargeoffDate() == null ? "" : DateUtils.format(amLoanAccountInfo.getChargeoffDate(),DateUtils.DATE_PATTERN_ANOTHER)) + ReportingConstant.separator_union);
        //107 收回标志 0 否 1 是
        if(ReportingConstant.ACCOUNT_STATUS_7.equals(amLoanAccountInfo.getAccountStatus()) ||
                ReportingConstant.ACCOUNT_STATUS_8.equals(amLoanAccountInfo.getAccountStatus())) {
            sb.append("1" + ReportingConstant.separator_union);
        }else{
            sb.append("0" + ReportingConstant.separator_union);
        }
        //108 核销收回日期
        sb.append("" + ReportingConstant.separator_union);
        //109 核销收回金额
        sb.append("0" + ReportingConstant.separator_union);
        //110 核销收回本金
        sb.append("0" + ReportingConstant.separator_union);
        //111 核销收回表内利息
        sb.append("0" + ReportingConstant.separator_union);
        //112 核销收回表外利息
        sb.append("0" + ReportingConstant.separator_union);
        //113 核销收回柜员号
        sb.append("" + ReportingConstant.separator_union);
        //114 约定还款银行支付行号
        sb.append("" + ReportingConstant.separator_union);
        //115 约定还款银行名称
        sb.append("" + ReportingConstant.separator_union);
        //116 银行出资比例
        sb.append("0" + ReportingConstant.separator_union);

        //查询罚息利率参数
        BigDecimal penaltyRate = BigDecimal.ZERO;
        PrPenaltyRateTableRes prPenaltyRateTableRes = prPenaltyRateTableService.findByTenIdAndPanaltyId(amLoanMainInfo.getTenantId(),amLoanMainInfo.getPenaltyTableId());
        if(ReportingConstant.INCREASE_TYPE_0.equals(prPenaltyRateTableRes.getIncreaseType())){
            penaltyRate = amLoanMainInfo.getOrigDailyRate().add(prPenaltyRateTableRes.getIncreaseNum()).multiply(new BigDecimal(36000));
        }else if(ReportingConstant.INCREASE_TYPE_1.equals(prPenaltyRateTableRes.getIncreaseType())){
            penaltyRate = amLoanMainInfo.getOrigDailyRate().multiply(new BigDecimal(1).add(prPenaltyRateTableRes.getIncreaseNum())).multiply(new BigDecimal(36000));
        }
        //117 罚息利率
        sb.append(df2.format(penaltyRate) + ReportingConstant.separator_union);
        //118 银团贷款标识
        sb.append("" + ReportingConstant.separator_union);
        //119 银团编号
        sb.append("" + ReportingConstant.separator_union);
        //120 贷款发放人编号
        sb.append("" + ReportingConstant.separator_union);
        //121 贷款发放人名称
        sb.append("" + ReportingConstant.separator_union);
        //122 源系统标识
        SystemParameterRes sourceId = systemParameterService.findByParamCode(ReportingConstant.SYS_SOURCE_ID,amLoanMainInfo.getTenantId());
        sb.append(sourceId.getParamValue() + ReportingConstant.separator_union);
        //123 贷款类型
        sb.append("BB");

        return sb.toString();
    }

    @Override
    public String createCertificateInfoFileMessage(CmCustomerFirstLevel cmCustomerFirstLevel) throws TxnException {
        //按照时间查询客户二级信息表 判断是否需要生成对应文件
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(cmCustomerFirstLevel.getOrganizationId());

        BtBatchStatus statuses = extBtBatchStatusMapper.selectByStatusAndJobName(ReportingConstant.BATCH_SATTUS_2,
                ReportingConstant.CUTOVER_END,org.getTenantId(),org.getToday());
        Date updateTime = null;
        if(null != statuses){
            updateTime = statuses.getCreateTime();
        }

        CmCustomerSecondLevel cmCustomerSecondLevel = extCmCustomerSecondLevelMapper.selectByUpdateTimeAndCustId(cmCustomerFirstLevel.getTenantId(),cmCustomerFirstLevel.getCustomerId(),
                updateTime, null);

        if(cmCustomerSecondLevel == null){
            return null;
        }

        //查询客户地址信息 只获取家庭
        CmCustomerAddressInfo Info = new CmCustomerAddressInfo();
        Info.setTenantId(cmCustomerSecondLevel.getTenantId());
        Info.setCustomerId(cmCustomerSecondLevel.getCustomerId());
        Info.setAddressType(ReportingConstant.ADDRESS_TYPE_1);
        Info.setAddressStatus(ReportingConstant.YES_FLAG);
        List<CmCustomerAddressInfo> addressInfos = extCmCustomerAddressInfoMapper.selectByCondSelective(Info);

        List<AddressInfoRes> addressList = customerService.getAddressList(cmCustomerSecondLevel.getChannel(),
                cmCustomerSecondLevel.getCustomerId(),cmCustomerSecondLevel.getTenantId());

        StringBuffer sb = new StringBuffer();
        //1 资源项ID 客户号+手机号
        sb.append(handleCustomerId(cmCustomerSecondLevel.getCustomerId(),cmCustomerSecondLevel.getTenantId()) +cmCustomerSecondLevel.getMobile() + ReportingConstant.separator_union);
        //2 登记ID
        sb.append(cmCustomerFirstLevel.getIdNumber() + ReportingConstant.separator_union);
        //3 名称
        sb.append("身份证" + ReportingConstant.separator_union);
        //4 编号
        sb.append(cmCustomerFirstLevel.getIdNumber() + ReportingConstant.separator_union);
        //5 证件项类型 10 开户核准证
        sb.append("10" + ReportingConstant.separator_union);
        //6 发证日期
        String bigDate = cmCustomerFirstLevel.getIdEffectiveDate().replaceAll("-","");
        sb.append(bigDate + ReportingConstant.separator_union);
        //7 结束有效日期
        String end = cmCustomerFirstLevel.getIdExpireDate().replaceAll("-","");
        sb.append(end + ReportingConstant.separator_union);
        //8 证件状态
        sb.append("1" + ReportingConstant.separator_union);
        //9 发证机构
        sb.append("" + ReportingConstant.separator_union);

        String addressMess = "";
        if(CollectionUtils.isNotEmpty(addressList)){
            addressMess = addressInfos.get(0).getAddress();
        }
        //10 证件地址
        sb.append(handleAddress(addressMess) + ReportingConstant.separator_union);
        //11 年检日期
        sb.append("" + ReportingConstant.separator_union);
        //12 创建日期
        sb.append("" + ReportingConstant.separator_union);
        //13 创建人
        sb.append("" + ReportingConstant.separator_union);
        //13 修改日期
        sb.append("" + ReportingConstant.separator_union);
        //14 修改人
        sb.append("" + ReportingConstant.separator_union);
        //15 租户ID
        sb.append(cmCustomerSecondLevel.getTenantId() + ReportingConstant.separator_union);
        //16 源系统标识
        SystemParameterRes sourceIdRes = systemParameterService.findByParamCode(ReportingConstant.SYS_SOURCE_ID,cmCustomerSecondLevel.getTenantId());
        sb.append(sourceIdRes.getParamValue());

        return sb.toString();
    }

    @Override
    public String createAccruedSerialFileMessage(TlInterestAccrualLog log) throws TxnException {
        //获取订单信息
        AmLoanAccountInfo amLoanAccountInfo = extAmLoanAccountInfoMapper.selectByLoanId(log.getLoanId(),log.getCustomerId(),log.getTenantId());
        //获取产品信息
        PrProductTable pro = productTableService.findProByProIdAndOrgId(amLoanAccountInfo.getProductId(),amLoanAccountInfo.getOrganizationId(),amLoanAccountInfo.getTenantId());

        StringBuffer sb = new StringBuffer();
        //1 机构编号
        SystemParameterRes orgRes = systemParameterService.findByParamCode(ReportingConstant.SYS_ORGNO,amLoanAccountInfo.getTenantId());
        sb.append(orgRes.getParamValue() + ReportingConstant.separator_union);
        //2 信息ID
        String swqNum = log.getAccountId().substring(log.getAccountId().length() - 24,log.getAccountId().length());
        String busiDate = DateUtils.format(log.getAccrualDate(),DateUtils.DATE_PATTERN_ANOTHER);
        sb.append(swqNum + busiDate + ReportingConstant.separator_union);
        //3 用户编号
        sb.append(handleCustomerId(log.getCustomerId(),log.getTenantId()) + ReportingConstant.separator_union);
        //4 借据id
        sb.append(subLoanId(log.getLoanId(),log.getTenantId()) + ReportingConstant.separator_union);
        //5 当前其次
        sb.append(amLoanAccountInfo.getCastTenor() + ReportingConstant.separator_union);
        //6 产品ID
        sb.append(pro.getId() + ReportingConstant.separator_union);
        //7 出资机构
        sb.append("" + ReportingConstant.separator_union);
        //8 加盟商
        sb.append("" + ReportingConstant.separator_union);
        //9 担保机构
        sb.append("" + ReportingConstant.separator_union);
        //10 记账流水号
        sb.append("" + ReportingConstant.separator_union);
        //11 业务流水号
        sb.append("" + ReportingConstant.separator_union);
        //12 渠道流水号
        sb.append("" + ReportingConstant.separator_union);
        //13 账务日期
        sb.append(busiDate + ReportingConstant.separator_union);
        //14 计提利息
        if(log.getAccountType().equals(ReportingConstant.INTEREST_ACCRUAL_TYPE_66)){
            sb.append(log.getAccrualProvision().setScale(4, BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
        }else{
            sb.append("" + ReportingConstant.separator_union);
        }
        //15 计提罚息 复利也算罚息
        if(log.getAccountType().equals(ReportingConstant.INTEREST_ACCRUAL_TYPE_10)||
                log.getAccountType().equals(ReportingConstant.INTEREST_ACCRUAL_TYPE_20)){
            sb.append(log.getAccrualProvision().setScale(4, BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
        }else{
            sb.append("0" + ReportingConstant.separator_union);
        }
        //16 计提账户管理费
        sb.append("0" + ReportingConstant.separator_union);
        //17 计提其他费用
        sb.append("0" + ReportingConstant.separator_union);
        //18 本次计提利息
        if(log.getAccountType().equals(ReportingConstant.INTEREST_ACCRUAL_TYPE_66)){
            sb.append(log.getAccrualProvision().setScale(4, BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
        }else{
            sb.append("" + ReportingConstant.separator_union);
        }
        //19 本次计提罚息
        if(log.getAccountType().equals(ReportingConstant.INTEREST_ACCRUAL_TYPE_10)||
                log.getAccountType().equals(ReportingConstant.INTEREST_ACCRUAL_TYPE_20)){
            sb.append(log.getAccrualProvision().setScale(4, BigDecimal.ROUND_DOWN) + ReportingConstant.separator_union);
        }else{
            sb.append("" + ReportingConstant.separator_union);
        }
        //20 本次计提账户管理费
        sb.append("0" + ReportingConstant.separator_union);
        //21 本次计提其他费用
        sb.append("0" + ReportingConstant.separator_union);
        //22 创建时间
        sb.append("" + ReportingConstant.separator_union);
        //23 修改时间
        sb.append("" + ReportingConstant.separator_union);
        //24 源系统标识
        SystemParameterRes sourceIdRes = systemParameterService.findByParamCode(ReportingConstant.SYS_SOURCE_ID,amLoanAccountInfo.getTenantId());
        sb.append(sourceIdRes.getParamValue());

        return sb.toString();
    }

    @Override
    public String createContractFileMessage(AmLoanAccountInfo amLoanAccountInfo) throws TxnException {
        //查询客户信息
        CustomerRes customer = customerService.getCustomerByChannelAndCustomerIdAndTensnId(amLoanAccountInfo.getChannel(),
                amLoanAccountInfo.getCustomerId(),amLoanAccountInfo.getTenantId());

        AmLoanMainInfo mainInfo = extAmLoanMainInfoMapper.selectByLoanIdAndCusId(amLoanAccountInfo.getLoanId(),amLoanAccountInfo.getCustomerId(),amLoanAccountInfo.getTenantId());

        //查询延滞交易账户
        AmDelinquencyInfo amDelinquencyInfo = extAmDelinquencyInfoMapper.getMinDelqByStatus(mainInfo.getLoanId(),mainInfo.getCustomerId(),mainInfo.getTenantId(),ReportingConstant.ACCOUNT_STATUS_1);

        DecimalFormat df2=new DecimalFormat("0.000000");

        StringBuffer sb = new StringBuffer();
        //1 租户号
        sb.append(amLoanAccountInfo.getTenantId() + ReportingConstant.separator_union);
        //2 合同号
        sb.append(subLoanId(amLoanAccountInfo.getLoanId(),amLoanAccountInfo.getTenantId()) + ReportingConstant.separator_union);
        //3 用户编号
        sb.append(handleCustomerId(amLoanAccountInfo.getCustomerId(),amLoanAccountInfo.getTenantId()) + ReportingConstant.separator_union);
        //4 优惠编号
        sb.append("" + ReportingConstant.separator_union);
        //5 放款用户编号
        sb.append(handleCustomerId(amLoanAccountInfo.getCustomerId(),amLoanAccountInfo.getTenantId()) + ReportingConstant.separator_union);
        //6 还款用户
        sb.append(customer.getFirstLevel().getChineseName() + ReportingConstant.separator_union);
        //7 借款用户
        sb.append(customer.getFirstLevel().getChineseName() + ReportingConstant.separator_union);
        //8 收款用户
        sb.append(customer.getFirstLevel().getChineseName() + ReportingConstant.separator_union);
        //9 证件类型 10 开户核准证
        sb.append("10" + ReportingConstant.separator_union);
        //10 证件编号
        sb.append(customer.getFirstLevel().getIdNumber() + ReportingConstant.separator_union);
        //11 客户名称
        sb.append(customer.getFirstLevel().getChineseName() + ReportingConstant.separator_union);
        //12 签约时间
        sb.append(DateUtils.format(amLoanAccountInfo.getCreateTime(),"yyyyMMdd HH:mm:ss") + ReportingConstant.separator_union);
        //13 生效时间
        sb.append(DateUtils.format(mainInfo.getTxnTime(),"yyyyMMdd HH:mm:ss") + ReportingConstant.separator_union);
        //14 创建时间
        sb.append(DateUtils.format(mainInfo.getCreateTime(),"yyyyMMdd HH:mm:ss") + ReportingConstant.separator_union);
        //15 更新时间
        sb.append("" + ReportingConstant.separator_union);
        //16 主合同号
        sb.append(subLoanId(amLoanAccountInfo.getLoanId(),amLoanAccountInfo.getTenantId()) + ReportingConstant.separator_union);
        //17 核心客户编号
        sb.append((customer.getFirstLevel().getEcifId() == null ? "": customer.getFirstLevel().getEcifId()) + ReportingConstant.separator_union);
        //18 业务办理机构
        SystemParameterRes orgRes = systemParameterService.findByParamCode(ReportingConstant.SYS_ORGNO,amLoanAccountInfo.getTenantId());
        sb.append(orgRes.getParamValue() + ReportingConstant.separator_union);
        //19 币种
        sb.append("CNY" + ReportingConstant.separator_union);
        //20 合同金额
        sb.append(mainInfo.getLoanAmount() + ReportingConstant.separator_union);
        //21 期限月
        sb.append(mainInfo.getTotalTenor() + ReportingConstant.separator_union);
        //22 合同开始日期
        sb.append(DateUtils.format(mainInfo.getInterestStartDate(),DateUtils.DATE_PATTERN_ANOTHER) + ReportingConstant.separator_union);
        //23 合同结束日期
        sb.append(DateUtils.format(mainInfo.getLastPaymentDate(),DateUtils.DATE_PATTERN_ANOTHER) + ReportingConstant.separator_union);
        //24 合同签订日期
        sb.append(DateUtils.format(mainInfo.getInterestStartDate(),DateUtils.DATE_PATTERN_ANOTHER) + ReportingConstant.separator_union);
        //25 终结日期
        sb.append((amLoanAccountInfo.getPayoffDate() == null ? "":DateUtils.format(amLoanAccountInfo.getPayoffDate(),DateUtils.DATE_PATTERN_ANOTHER)) + ReportingConstant.separator_union);
        //26 逾期日期
        String delqDate = "";
        if(null != amDelinquencyInfo){
            delqDate = DateUtils.format(amDelinquencyInfo.getDelqDate(),DateUtils.DATE_PATTERN_ANOTHER);
        }
        sb.append(delqDate + ReportingConstant.separator_union);
        //27 贷款五级分类
        sb.append(transFive(amLoanAccountInfo.getLoanClassify()) + ReportingConstant.separator_union);
        //28 还款方式
        String paymentMode="";
        switch (mainInfo.getAmortMethodTableId()){
            case "02" ://TXN 02 等额本息
                paymentMode="04";
                break;
            case "08" ://TXN 08 按月付息按年还本
                paymentMode="03";
                break;
        }
        sb.append(paymentMode + ReportingConstant.separator_union);
        //29 计息周期 5 不固定
        sb.append("5" + ReportingConstant.separator_union);
        //30 信贷产品类别 F021 消费贷款 F022 经营贷款
        if(ReportingConstant.UNION_DEFAULT_TENANT_ID.equals(amLoanAccountInfo.getTenantId())){
            sb.append("F021" + ReportingConstant.separator_union);
        }else{
            if(ReportingConstant.LOAN_TYPE_6.equals(mainInfo.getLoanType())){
                sb.append("F022" + ReportingConstant.separator_union);
            }else{
                sb.append("F021" + ReportingConstant.separator_union);
            }
        }

        //31 利率类型 RF01 固定利率
        sb.append("RF01" + ReportingConstant.separator_union);
        //32 年华利率百分比
        sb.append(df2.format(mainInfo.getInterestRate().multiply(new BigDecimal(100))) + ReportingConstant.separator_union);
        //33 利率浮动
        sb.append("0" + ReportingConstant.separator_union);
        //34 执行利率
        sb.append(df2.format(mainInfo.getInterestRate().multiply(new BigDecimal(100))) + ReportingConstant.separator_union);
        //35 担保方式
        if(ReportingConstant.UNION_DEFAULT_TENANT_ID.equals(mainInfo.getTenantId())){
            sb.append("01" + ReportingConstant.separator_union);
        }else{
            sb.append("99" + ReportingConstant.separator_union);
        }
        //36 客户经理工号
        SystemParameterRes custMgNo = systemParameterService.findByParamCode(ReportingConstant.SYS_CUST_MG_NO,mainInfo.getTenantId());
        sb.append(custMgNo.getParamValue() + ReportingConstant.separator_union);
        //37 贷款投向行业
        sb.append("999" + ReportingConstant.separator_union);
        //38 工业转型升级标识
        sb.append("2" + ReportingConstant.separator_union);
        //39 产业结构调整类型
        sb.append("1" + ReportingConstant.separator_union);
        //40 战略新兴产业类型
        sb.append("09" + ReportingConstant.separator_union);
        //41 是否国家限制行业
        sb.append("2" + ReportingConstant.separator_union);
        //42 贷款新规种类
        sb.append("10" + ReportingConstant.separator_union);
        //43 贷款期限
        int days2 = DateUtils.getDaysBetween(mainInfo.getLastPaymentDate(),mainInfo.getInterestStartDate());
        sb.append(days2 + ReportingConstant.separator_union);
        //44 支付方式/放款方式 10 -自主支付 20 -受托支付 30 -混合支付
        if(ReportingConstant.UNION_DEFAULT_TENANT_ID.equals(mainInfo.getTenantId())){
            sb.append("10" + ReportingConstant.separator_union);
        }else{
            //查询客户放款流水
            List<TlDisbursementLog> tlDisbursementLogList = extTlDisbursementLogMapper.selectBySumStatusAndLoanId(mainInfo.getLoanId(),mainInfo.getCustomerId(),mainInfo.getTenantId(),
                    ReportingConstant.DISBURSEMENT_LOG_SUM_STATUS_S);
            if(CollectionUtils.isEmpty(tlDisbursementLogList) || ReportingConstant.NO_FLAG.equals(tlDisbursementLogList.get(0).getEntrustedPayment())){
                sb.append("10" + ReportingConstant.separator_union);
            }else{
                sb.append("20" + ReportingConstant.separator_union);
            }
        }
        //45 资金来源
        sb.append("01" + ReportingConstant.separator_union);
        //46 贷款用途 9902其它消费性用途 9901 其它经营性用途
        if(ReportingConstant.UNION_DEFAULT_TENANT_ID.equals(amLoanAccountInfo.getTenantId())){
            sb.append("9902" + ReportingConstant.separator_union);
        }else{
            if(ReportingConstant.LOAN_TYPE_6.equals(mainInfo.getLoanType())){
                sb.append("9901" + ReportingConstant.separator_union);
            }else{
                sb.append("9902" + ReportingConstant.separator_union);
            }
        }
        //47 贷款投向地区
        sb.append("" + ReportingConstant.separator_union);
        //48 银团贷款标识
        sb.append("" + ReportingConstant.separator_union);
        //49 银团编号
        sb.append("" + ReportingConstant.separator_union);
        //50 银行出资比例
        sb.append("0" + ReportingConstant.separator_union);
        //51 贷款状态 1 正常
        sb.append("1" + ReportingConstant.separator_union);
        //52 备注1
        sb.append("" + ReportingConstant.separator_union);

        if(ReportingConstant.UNION_LS_TENANT_ID.equals(amLoanAccountInfo.getTenantId())){
            if(ReportingConstant.LOAN_TYPE_6.equals(mainInfo.getLoanType())){
                //经营贷
                SystemParameterRes aclgNoJy = systemParameterService.findByParamCode(ReportingConstant.LS_SYS_ACLG_NO_JY,mainInfo.getTenantId());
                SystemParameterRes aclgNoJy59201 = systemParameterService.findByParamCode(ReportingConstant.LS_SYS_ACLG_NO_59201_JY,mainInfo.getTenantId());
                SystemParameterRes aclgNoJy59301 = systemParameterService.findByParamCode(ReportingConstant.LS_SYS_ACLG_NO_59301_JY,mainInfo.getTenantId());
                //53 备注2
                sb.append(aclgNoJy.getParamValue() + ReportingConstant.separator_union);
                //54 备注3
                sb.append(aclgNoJy59201.getParamValue() + ReportingConstant.separator_union);
                //55 备注4
                sb.append(aclgNoJy59301.getParamValue() + ReportingConstant.separator_union);
            }else{
                //消费贷
                SystemParameterRes aclgNoXf = systemParameterService.findByParamCode(ReportingConstant.LS_SYS_ACLG_NO_XF,mainInfo.getTenantId());
                SystemParameterRes aclgNoXf59201 = systemParameterService.findByParamCode(ReportingConstant.LS_SYS_ACLG_NO_59201_XF,mainInfo.getTenantId());
                SystemParameterRes aclgNoXf59301 = systemParameterService.findByParamCode(ReportingConstant.LS_SYS_ACLG_NO_59301_XF,mainInfo.getTenantId());
                //53 备注2
                sb.append(aclgNoXf.getParamValue() + ReportingConstant.separator_union);
                //54 备注3
                sb.append(aclgNoXf59201.getParamValue() + ReportingConstant.separator_union);
                //55 备注4
                sb.append(aclgNoXf59301.getParamValue() + ReportingConstant.separator_union);
            }
        }else{
            //53 备注2
            sb.append("" + ReportingConstant.separator_union);
            //54 备注3
            sb.append("" + ReportingConstant.separator_union);
            //55 备注4
            sb.append("" + ReportingConstant.separator_union);
        }
        //56 备注5
        sb.append("" + ReportingConstant.separator_union);
        //57 源系统标识
        SystemParameterRes source = systemParameterService.findByParamCode(ReportingConstant.SYS_SOURCE_ID,mainInfo.getTenantId());
        sb.append(source.getParamValue() + ReportingConstant.separator_union);
        //58 贷款类型
        sb.append("BB");

        return sb.toString();
    }

    @Override
    public String createRepayPlanFileMessage(AmRepaymentPlanInfo planInfo) throws TxnException {
        StringBuffer sb = new StringBuffer();
        AmLoanMainInfo mainInfo = extAmLoanMainInfoMapper.selectByLoanIdAndCusId(planInfo.getLoanId(),planInfo.getCustomerId(),planInfo.getTenantId());
        //查询产品信息
        PrProductTable pro = productTableService.findProByProIdAndOrgId(mainInfo.getProductId(),mainInfo.getOrganizationId(),mainInfo.getTenantId());

        //查询还款分配记录
        TlPaymentAllocationLog tlPaymentAllocationLog = new TlPaymentAllocationLog();
        tlPaymentAllocationLog.setCustomerId(planInfo.getCustomerId());
        tlPaymentAllocationLog.setTenantId(planInfo.getTenantId());
        tlPaymentAllocationLog.setLoanId(planInfo.getLoanId());
        tlPaymentAllocationLog.setBillingTenor(planInfo.getBillingTenor());
        List<TlPaymentAllocationLog> tlPaymentAllocationLogList = extTlPaymentAllocationLogMapper.selectListByCondition(tlPaymentAllocationLog);

        //1 租户号
        sb.append(planInfo.getTenantId() + ReportingConstant.separator_union);
        //2 借据号
        sb.append(subLoanId(planInfo.getLoanId(),planInfo.getTenantId()) + ReportingConstant.separator_union );
        //3 借款人
        sb.append(handleCustomerId(planInfo.getCustomerId(),planInfo.getTenantId()) + ReportingConstant.separator_union );
        //4 商户号
        SystemParameterRes merchantRes = systemParameterService.findByParamCode(ReportingConstant.SYS_MERCHANT_ID,planInfo.getTenantId());
        sb.append(merchantRes.getParamValue() + ReportingConstant.separator_union );
        //5 合作方用户编号
        sb.append("" + ReportingConstant.separator_union );
        //6 总期次
        sb.append(mainInfo.getTotalTenor() + ReportingConstant.separator_union );
        //7 当前期次
        sb.append(planInfo.getBillingTenor() + ReportingConstant.separator_union );
        //8 合同编号
        sb.append(subLoanId(planInfo.getLoanId(),planInfo.getTenantId()) + ReportingConstant.separator_union );
        //9 托管类型 1-非托管 2-托管
        sb.append("1" + ReportingConstant.separator_union );
        //10 开始时间
        sb.append(DateUtils.format(mainInfo.getInterestStartDate(),DateUtils.DATE_PATTERN_ANOTHER) + ReportingConstant.separator_union );

        String day = "";
        if(planInfo.getTransactionDate() != null){
            day = DateUtils.getDaysBetween(planInfo.getTransactionDate(),planInfo.getPaymentDueDate()) + "";
        }else{
            day = "0";
        }
        //11 收益天数
        sb.append(day + ReportingConstant.separator_union );
        //12 预期还款金额
        sb.append(planInfo.getTotalAmount() + ReportingConstant.separator_union );
        //13 应还时间
        sb.append(DateUtils.format(planInfo.getPaymentDueDate(),DateUtils.DATE_PATTERN_ANOTHER) + ReportingConstant.separator_union );
        //14 宽限日期
        Date graceDate = DateUtils.addDay(planInfo.getPaymentDueDate(),pro.getGraceDays());//产品表默认值0
        sb.append(DateUtils.format(graceDate,DateUtils.DATE_PATTERN_ANOTHER) + ReportingConstant.separator_union );
        //15 应还本金
        sb.append(planInfo.getPrincipalAmount().setScale(4) + ReportingConstant.separator_union );
        //16 应还利息
        sb.append(planInfo.getInterestAmount().setScale(4) + ReportingConstant.separator_union );
        //17 应还手续费
        sb.append(planInfo.getFeeAmount().setScale(4) + ReportingConstant.separator_union );
        //18 应还账户管理费
        sb.append("0" + ReportingConstant.separator_union );

        String postDate = "00000000";//还款日期

        BigDecimal repayTotalAmt = BigDecimal.ZERO;//已还总金额
        BigDecimal repayPrincipalAmt = BigDecimal.ZERO;//已还本金
        BigDecimal repayIntAmt = BigDecimal.ZERO;//已还利息
        BigDecimal repayPenIntAmt = BigDecimal.ZERO;//已还罚息
        String seqNo = "";

        if(CollectionUtils.isNotEmpty(tlPaymentAllocationLogList)){
            for(TlPaymentAllocationLog allocationLog : tlPaymentAllocationLogList){
                repayTotalAmt = repayTotalAmt.add(allocationLog.getPostingAmount());
                if(ReportingConstant.ACCOUNT_TYPE_06.equals(allocationLog.getConnectAccountType())){
                    repayPrincipalAmt = repayPrincipalAmt.add(allocationLog.getPostingAmount());
                }else if(ReportingConstant.ACCOUNT_TYPE_04.equals(allocationLog.getConnectAccountType())){
                    repayIntAmt = repayIntAmt.add(allocationLog.getPostingAmount());
                }else if(ReportingConstant.ACCOUNT_TYPE_11.equals(allocationLog.getConnectAccountType())){
                    repayPenIntAmt = repayPenIntAmt.add(allocationLog.getPostingAmount());
                }else if(ReportingConstant.ACCOUNT_TYPE_12.equals(allocationLog.getConnectAccountType())){
                    repayPenIntAmt = repayPenIntAmt.add(allocationLog.getPostingAmount());
                }
            }
            postDate = DateUtils.format(tlPaymentAllocationLogList.get(0).getPostingDate(),DateUtils.DATE_PATTERN_ANOTHER);
            seqNo = tlPaymentAllocationLogList.get(0).getSeqNo();
        }

        //19 最近实还金额
        sb.append(repayTotalAmt.setScale(4) + ReportingConstant.separator_union );
        //20 最近实还时间
        sb.append(postDate + ReportingConstant.separator_union );

        if(ReportingConstant.LOAN_PLAN_STATUS_7.equals(planInfo.getPlanStatus())||
                ReportingConstant.LOAN_PLAN_STATUS_8.equals(planInfo.getPlanStatus())){
            //21 剩余应还总金额
            sb.append("0" + ReportingConstant.separator_union );
            //22 剩余应还本金
            sb.append("0" + ReportingConstant.separator_union );
            //23 剩余应还利息
            sb.append("0" + ReportingConstant.separator_union );
            //24 剩余应还手续费
            sb.append("0" + ReportingConstant.separator_union );
            //25 剩余应还账户管理费
            sb.append("0" + ReportingConstant.separator_union );
        }else{
            //21 剩余应还总金额
            BigDecimal repayTotalAmount = planInfo.getRepayPrincipal().add(planInfo.getRepayInterest()).add(planInfo.getRepayPenaltyInterest()).add(planInfo.getRepayCompoundInterest()).add(planInfo.getRepayFee());
            sb.append(planInfo.getTotalAmount().subtract(repayTotalAmount).setScale(4) + ReportingConstant.separator_union );
            //22 剩余应还本金
            sb.append(planInfo.getPrincipalAmount().subtract(planInfo.getRepayPrincipal()).setScale(4) + ReportingConstant.separator_union );
            //23 剩余应还利息
            sb.append(planInfo.getInterestAmount().subtract(planInfo.getRepayInterest()).setScale(4) + ReportingConstant.separator_union );
            //24 剩余应还手续费
            sb.append("0" + ReportingConstant.separator_union );
            //25 剩余应还账户管理费
            sb.append("0" + ReportingConstant.separator_union );
        }
        //还款计划状态 EnumRepayPlanStatus 1:待还款2:部分还款3:已还款4:逾期5:逾期部分还款6:逾期还款7:已结清

        String tr = "";
        if (ReportingConstant.LOAN_PLAN_STATUS_0.equals(planInfo.getPlanStatus())
                || ReportingConstant.LOAN_PLAN_STATUS_1.equals(planInfo.getPlanStatus())) {
            tr = "1";
        }
        if (ReportingConstant.LOAN_PLAN_STATUS_7.equals(planInfo.getPlanStatus())
                || ReportingConstant.LOAN_PLAN_STATUS_8.equals(planInfo.getPlanStatus())) {
            tr = "7";
        }
        if (ReportingConstant.LOAN_PLAN_STATUS_2.equals(planInfo.getPlanStatus())) {
            tr = "4";
        }
        //26 还款计划状态
        sb.append(tr + ReportingConstant.separator_union );
        //27 应还用户
        sb.append(handleCustomerId(planInfo.getCustomerId(),planInfo.getTenantId()) + ReportingConstant.separator_union );
        //28 实还用户
        sb.append(handleCustomerId(planInfo.getCustomerId(),planInfo.getTenantId()) + ReportingConstant.separator_union );
        //29 免息天数
        sb.append("0" + ReportingConstant.separator_union );

        BigDecimal penIntAmt = BigDecimal.ZERO;

        //如果还款计划逾期，查询罚息累计账户
        if(ReportingConstant.LOAN_PLAN_STATUS_2.equals(planInfo.getPlanStatus())){
            List<AmInterestAccrualInfo> penAccrualInfo = extAmInterestAccrualInfoMapper.selectByStatusAndType(planInfo.getLoanId(),planInfo.getCustomerId(),planInfo.getTenantId(),
                    Arrays.asList(ReportingConstant.ACCOUNT_STATUS_1),Arrays.asList(ReportingConstant.INTEREST_ACCRUAL_TYPE_10,ReportingConstant.INTEREST_ACCRUAL_TYPE_20),Arrays.asList(planInfo.getBillingTenor()));
            if(CollectionUtils.isNotEmpty(penAccrualInfo)){
                for(AmInterestAccrualInfo amInterestAccrualInfo : penAccrualInfo){
                    penIntAmt = penIntAmt.add(amInterestAccrualInfo.getAccrualTotalAccruInterest());
                }
            }
        }
        //30 罚息计算时间
        sb.append("" + ReportingConstant.separator_union );
        //31 应付逾期罚息 累计罚息 复利 + 已还罚息
        sb.append(penIntAmt.add(repayPenIntAmt).setScale(4) + ReportingConstant.separator_union );
        //32 剩余逾期罚息
        sb.append(penIntAmt.setScale(4) + ReportingConstant.separator_union );
        //33 临时缓存罚息
        sb.append("0" + ReportingConstant.separator_union );
        //34 结算罚息
        sb.append("0" + ReportingConstant.separator_union );
        //35 还款手续费
        sb.append("0" + ReportingConstant.separator_union );
        //36 提前还款手续费
        sb.append("0" + ReportingConstant.separator_union );
        //37 剩余本金
        sb.append(planInfo.getPrincipalAmount().subtract(planInfo.getRepayPrincipal()).setScale(4) + ReportingConstant.separator_union );
        //38 还款流水
        sb.append("" + ReportingConstant.separator_union );
        //39 逾期天数
        sb.append(planInfo.getDelqDays() + ReportingConstant.separator_union );
        //40 渠道编号
        sb.append("" + ReportingConstant.separator_union );
        //41 创建时间
        sb.append("" + ReportingConstant.separator_union );
        //42 更新时间
        sb.append("" + ReportingConstant.separator_union );
        //43 虚户ID
        sb.append("" + ReportingConstant.separator_union );
        //44 源系统标识
        SystemParameterRes sourceRes = systemParameterService.findByParamCode(ReportingConstant.SYS_SOURCE_ID,planInfo.getTenantId());
        sb.append(sourceRes.getParamValue() + ReportingConstant.separator_union );
        //45 账号
        sb.append("" + ReportingConstant.separator_union );

        //0-未还 1-已还清/结清
        if(ReportingConstant.LOAN_PLAN_STATUS_7.equals(planInfo.getPlanStatus()) ||
                ReportingConstant.LOAN_PLAN_STATUS_8.equals(planInfo.getPlanStatus())){
            //46 还款标志
            sb.append("1");
        }else{
            //46 还款标志
            sb.append("0");
        }

        return sb.toString();
    }

    @Override
    public String createAddressFileMessage(CmCustomerAddressInfo addressInfo) throws TxnException {
        StringBuffer sb = new StringBuffer();
        //1 联系点ID
        sb.append(handleCustomerId(addressInfo.getCustomerId(),addressInfo.getTenantId()) + addressInfo.getId() + ReportingConstant.separator_union);
        //2 地址分类代码
        if(ReportingConstant.ADDRESS_TYPE_1.equals(addressInfo.getAddressType())){
            sb.append("22" + ReportingConstant.separator_union);
        }else if(ReportingConstant.ADDRESS_TYPE_2.equals(addressInfo.getAddressType())){
            sb.append("32" + ReportingConstant.separator_union);
        }else if(ReportingConstant.ADDRESS_TYPE_0.equals(addressInfo.getAddressType())){
            sb.append("23" + ReportingConstant.separator_union);
        }else if(ReportingConstant.ADDRESS_TYPE_3.equals(addressInfo.getAddressType())){
            sb.append("21" + ReportingConstant.separator_union);
        }else if(ReportingConstant.ADDRESS_TYPE_4.equals(addressInfo.getAddressType())){
            sb.append("25" + ReportingConstant.separator_union);
        }
        //3 省
        sb.append((addressInfo.getProvince()==null? "":addressInfo.getProvince()) + ReportingConstant.separator_union);
        //4 市
        sb.append((addressInfo.getCity()==null?"":addressInfo.getCity()) + ReportingConstant.separator_union);
        //5 全地址
        sb.append(handleAddress(addressInfo.getAddress()) + ReportingConstant.separator_union);
        //6 经度
        sb.append("" + ReportingConstant.separator_union);
        //7 纬度
        sb.append("" + ReportingConstant.separator_union);
        //8 所属名称
        sb.append("" + ReportingConstant.separator_union);
        //9 邮政编码
        sb.append("" + ReportingConstant.separator_union);
        //10 区
        sb.append((addressInfo.getDistrict() == null ? "": addressInfo.getDistrict()) + ReportingConstant.separator_union);
        //11 国家
        sb.append("CHN" + ReportingConstant.separator_union);
        //12 居住情况
        sb.append("9" + ReportingConstant.separator_union);
        //13 是否收货地址
        sb.append("" + ReportingConstant.separator_union);
        //14 收货人信息ID
        sb.append("" + ReportingConstant.separator_union);
        //15 创建日期
        sb.append(DateUtils.format(addressInfo.getCreateTime(),DateUtils.DATE_PATTERN_ANOTHER) + ReportingConstant.separator_union);
        //16 创建人
        sb.append("" + ReportingConstant.separator_union);
        //17 修改日期
        sb.append("" + ReportingConstant.separator_union);
        //18 修改人
        sb.append("" + ReportingConstant.separator_union);
        //19 租户
        sb.append(addressInfo.getTenantId() + ReportingConstant.separator_union);
        //20 源系统标识
        SystemParameterRes sourceIdRes = systemParameterService.findByParamCode(ReportingConstant.SYS_SOURCE_ID,addressInfo.getTenantId());
        sb.append(sourceIdRes.getParamValue());

        return sb.toString();
    }

    @Override
    public String createCustResourceFileMessage(CmCustomerFirstLevel cmCustomerFirstLevel) throws TxnException {

        //按照时间查询客户二级信息表 判断是否需要生成对应文件
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(cmCustomerFirstLevel.getOrganizationId());

        BtBatchStatus statuses = extBtBatchStatusMapper.selectByStatusAndJobName(ReportingConstant.BATCH_SATTUS_2,
                ReportingConstant.CUTOVER_END,org.getTenantId(),org.getToday());
        Date updateTime = null;
        if(null != statuses){
            updateTime = statuses.getCreateTime();
        }

        CmCustomerSecondLevel secondLevel = extCmCustomerSecondLevelMapper.selectByUpdateTimeAndCustId(cmCustomerFirstLevel.getTenantId(),cmCustomerFirstLevel.getCustomerId(),
                updateTime, null);

        if(secondLevel == null){
            return null;
        }


        StringBuffer sb = new StringBuffer();
        //1 资源项ID
        sb.append(handleCustomerId(secondLevel.getCustomerId(),secondLevel.getTenantId()) + secondLevel.getMobile() + ReportingConstant.separator_union);
        //2 客户ID
        sb.append(handleCustomerId(secondLevel.getCustomerId(),secondLevel.getTenantId()) + ReportingConstant.separator_union);
        //3 资源项类型
        sb.append("0" + ReportingConstant.separator_union);
        //4 客户资源状态
        sb.append("" + ReportingConstant.separator_union);
        //5 资源项来源
        sb.append("" + ReportingConstant.separator_union);
        //6 创建日期
        sb.append("" + ReportingConstant.separator_union);
        //7 创建人
        sb.append("" + ReportingConstant.separator_union);
        //8 修改日期
        sb.append("" + ReportingConstant.separator_union);
        //9 修改人
        sb.append("" + ReportingConstant.separator_union);
        //10 租户
        sb.append(secondLevel.getTenantId() + ReportingConstant.separator_union);
        //11 源系统标识
        SystemParameterRes res = systemParameterService.findByParamCode(ReportingConstant.SYS_SOURCE_ID,secondLevel.getTenantId());
        sb.append(res.getParamValue());

        return sb.toString();
    }

    @Override
    public String createCustTelFileMessage(CmCustomerFirstLevel cmCustomerFirstLevel) throws TxnException {

        //按照时间查询客户二级信息表 判断是否需要生成对应文件
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(cmCustomerFirstLevel.getOrganizationId());

        BtBatchStatus statuses = extBtBatchStatusMapper.selectByStatusAndJobName(ReportingConstant.BATCH_SATTUS_2,
                ReportingConstant.CUTOVER_END,org.getTenantId(),org.getToday());
        Date updateTime = null;
        if(null != statuses){
            updateTime = statuses.getCreateTime();
        }

        CmCustomerSecondLevel secondLevel = extCmCustomerSecondLevelMapper.selectByUpdateTimeAndCustId(cmCustomerFirstLevel.getTenantId(),cmCustomerFirstLevel.getCustomerId(),
                updateTime, null);

        if(secondLevel == null){
            return null;
        }


        StringBuffer sb = new StringBuffer();
        //1 联系点ID
        sb.append(handleCustomerId(secondLevel.getCustomerId(),secondLevel.getTenantId()) + secondLevel.getUserId() + ReportingConstant.separator_union);
        //2 电话分类代码 电话分类代码"200", "个人客户电话"),
        sb.append("200" + ReportingConstant.separator_union);
        //3 区号
        sb.append("" + ReportingConstant.separator_union);
        //4 电话号
        sb.append(secondLevel.getMobile() + ReportingConstant.separator_union);
        //5 创建日期
        sb.append(DateUtils.format(secondLevel.getCreateTime(),DateUtils.DATE_PATTERN_ANOTHER) + ReportingConstant.separator_union);
        //6 创建人
        sb.append("" + ReportingConstant.separator_union);
        //7 修改日期
        sb.append("" + ReportingConstant.separator_union);
        //8 修改人
        sb.append("" + ReportingConstant.separator_union);
        //9 租户ID
        sb.append(secondLevel.getTenantId() + ReportingConstant.separator_union);
        //10 源系统标识
        SystemParameterRes sourceRes = systemParameterService.findByParamCode(ReportingConstant.SYS_SOURCE_ID,secondLevel.getTenantId());
        sb.append(sourceRes.getParamValue());

        return sb.toString();
    }

    @Override
    public String createPersonalFileMessage(CmCustomerFirstLevel cmCustomerFirstLevel) throws TxnException {
        //按照时间查询客户二级信息表 判断是否需要生成对应文件
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(cmCustomerFirstLevel.getOrganizationId());

        BtBatchStatus statuses = extBtBatchStatusMapper.selectByStatusAndJobName(ReportingConstant.BATCH_SATTUS_2,
                ReportingConstant.CUTOVER_END,org.getTenantId(),org.getToday());
        Date updateTime = null;
        if(null != statuses){
            updateTime = statuses.getCreateTime();
        }

        CmCustomerSecondLevel secondLevel = extCmCustomerSecondLevelMapper.selectByUpdateTimeAndCustId(cmCustomerFirstLevel.getTenantId(),cmCustomerFirstLevel.getCustomerId(),
                updateTime, null);

        if(secondLevel == null){
            return null;
        }

        //查询配偶信息
        CmCustomerContactInfo contactInfo = new CmCustomerContactInfo();
        contactInfo.setTenantId(secondLevel.getTenantId());
        contactInfo.setCustomerId(secondLevel.getCustomerId());
        contactInfo.setRelationship("01");//01 配偶
        List<CmCustomerContactInfo> contactInfos = extCmCustomerContactInfoMapper.selectByCondSelective(contactInfo);

        //获取地址信息
        ArrayList<AddressInfoRes> addressInfoRes = customerService.getAddressList(secondLevel.getChannel(),secondLevel.getCustomerId(),secondLevel.getTenantId());
        String zipCode = "";//居住地邮编
        String compAddress = "";//公司地址
        for(AddressInfoRes InfoRes : addressInfoRes){
            if(ReportingConstant.ADDRESS_TYPE_1.equals(InfoRes.getAddressType())){
                zipCode = InfoRes.getZipcode();
            }
            if(ReportingConstant.ADDRESS_TYPE_3.equals(InfoRes.getAddressType())){
                compAddress = InfoRes.getAddress();
            }
        }
        //查询绑卡信息
        CmCustomerBankcardInfo bankcardInfo = bankCardService.getBankCardByCustomerId(secondLevel.getCustomerId(),"Y",
                secondLevel.getChannel(),secondLevel.getTenantId());

        StringBuffer sb = new StringBuffer();
        //1 客户ID
        sb.append(handleCustomerId(secondLevel.getCustomerId(),secondLevel.getTenantId()) + ReportingConstant.separator_union);
        //2 客户姓名
        sb.append(cmCustomerFirstLevel.getChineseName() + ReportingConstant.separator_union);
        //3 英文名称
        sb.append("" + ReportingConstant.separator_union);
        //4 简称
        sb.append("" + ReportingConstant.separator_union);
        //5 性别 1:男2:女9:未说明的性别
        sb.append(cmCustomerFirstLevel.getSex() + ReportingConstant.separator_union);
        //6 学历
        sb.append("99" + ReportingConstant.separator_union);
        //7 政治面貌
        sb.append("" + ReportingConstant.separator_union);
        //8 国籍地区
        sb.append("CHN" + ReportingConstant.separator_union);
        //9 民族
        sb.append("" + ReportingConstant.separator_union);
        //10 宗教
        sb.append("" + ReportingConstant.separator_union);
        //11 年龄
        sb.append(getAge(cmCustomerFirstLevel.getIdNumber()) + ReportingConstant.separator_union);
        //12 婚姻状况
        sb.append((secondLevel.getMaritalStatus()==null?"":secondLevel.getMaritalStatus()) + ReportingConstant.separator_union);
        //13 创建日期
        sb.append(DateUtils.format(secondLevel.getCreateTime(),"yyyyMMdd HH:mm:ss") + ReportingConstant.separator_union);
        //14 创建人
        sb.append("" + ReportingConstant.separator_union);
        //15 修改日期
        sb.append("" + ReportingConstant.separator_union);
        //16 修改人
        sb.append("" + ReportingConstant.separator_union);
        //17 租户ID
        sb.append(secondLevel.getTenantId() + ReportingConstant.separator_union);
        //18 业务办理机构
        SystemParameterRes orgRes = systemParameterService.findByParamCode(ReportingConstant.SYS_ORGNO,secondLevel.getTenantId());
        sb.append(orgRes.getParamValue() + ReportingConstant.separator_union);
        //19 核心客户编号
        sb.append((cmCustomerFirstLevel.getEcifId() == null ? "" : cmCustomerFirstLevel.getEcifId()) + ReportingConstant.separator_union);
        //20 发证机关代码
        sb.append("" + ReportingConstant.separator_union);
        //21 居民标志
        sb.append("1" + ReportingConstant.separator_union);
        //22 境内/境外标志
        sb.append("1" + ReportingConstant.separator_union);
        //23 出生日期
        sb.append(DateUtils.format(cmCustomerFirstLevel.getBirthDate(),DateUtils.DATE_PATTERN_ANOTHER) + ReportingConstant.separator_union);
        //24 最高学位
        sb.append("999" + ReportingConstant.separator_union);


        if(CollectionUtils.isNotEmpty(contactInfos)){
            //25 配偶
            sb.append(contactInfos.get(0).getChineseName() + ReportingConstant.separator_union);
            //26 配偶联系电话
            sb.append(contactInfos.get(0).getMobile() + ReportingConstant.separator_union);
            //27 配偶移动电话
            sb.append(contactInfos.get(0).getMobile() + ReportingConstant.separator_union);
            //28 配偶证件类型
            sb.append("10" + ReportingConstant.separator_union);
            //29 配偶证件号码
            sb.append((contactInfos.get(0).getIdNumber() == null ? "" :contactInfos.get(0).getIdNumber()) + ReportingConstant.separator_union);
            //30 配偶客户号
            sb.append("" + ReportingConstant.separator_union);
            //31 配偶工作单位名称
            sb.append(handleAddress(contactInfos.get(0).getCompanyName() == null ? "" :contactInfos.get(0).getCompanyName())+ ReportingConstant.separator_union);
            //32 配偶工作单位地址
            sb.append(handleAddress(contactInfos.get(0).getCompanyAddress() == null ? "" :contactInfos.get(0).getCompanyAddress())+ ReportingConstant.separator_union);
            //33 配偶工作单位电话
            sb.append((contactInfos.get(0).getOfficePhone() == null ? "" :contactInfos.get(0).getOfficePhone())+ ReportingConstant.separator_union);
        }else{
            //25 配偶
            sb.append("" + ReportingConstant.separator_union);
            //26 配偶联系电话
            sb.append("" + ReportingConstant.separator_union);
            //27 配偶移动电话
            sb.append("" + ReportingConstant.separator_union);
            //28 配偶证件类型
            sb.append("" + ReportingConstant.separator_union);
            //29 配偶证件号码
            sb.append("" + ReportingConstant.separator_union);
            //30 配偶客户号
            sb.append("" + ReportingConstant.separator_union);
            //31 配偶工作单位名称
            sb.append("" + ReportingConstant.separator_union);
            //32 配偶工作单位地址
            sb.append("" + ReportingConstant.separator_union);
            //33 配偶工作单位电话
            sb.append("" + ReportingConstant.separator_union);
        }

        //34 国民经济部门
        sb.append("D01" + ReportingConstant.separator_union);
        //35 行业类别
        sb.append("100" + ReportingConstant.separator_union);
        //36 行政区划
        sb.append(cmCustomerFirstLevel.getIdNumber().substring(0,6) + ReportingConstant.separator_union);
        //37 即时通讯号
        sb.append("" + ReportingConstant.separator_union);
        //38 居住地邮政编码
        sb.append((zipCode == null ? "":zipCode) + ReportingConstant.separator_union);
        //39 居住状况
        sb.append("9" + ReportingConstant.separator_union);
        //40 职业
        sb.append((secondLevel.getOccuptionType()==null?"":secondLevel.getOccuptionType()) + ReportingConstant.separator_union);
        //41 职称
        sb.append("99" + ReportingConstant.separator_union);
        //42 职务
        sb.append("90" + ReportingConstant.separator_union);
        //43 工作单位名称
        sb.append(handleAddress(secondLevel.getCompanyName()==null?"":secondLevel.getCompanyName()) + ReportingConstant.separator_union);
        //44 工作单位电话
        sb.append((secondLevel.getCompanyPhone()==null?"": secondLevel.getCompanyPhone())+ ReportingConstant.separator_union);
        //45 工作单位性质
        sb.append((secondLevel.getCompanyAttribute()==null?"":secondLevel.getCompanyAttribute()) + ReportingConstant.separator_union);
        //46 工作单位地址
        sb.append(handleAddress(compAddress) + ReportingConstant.separator_union);
        //47 个人年收入
        sb.append("0" + ReportingConstant.separator_union);
        //48 月收入
        sb.append("0" + ReportingConstant.separator_union);
        //49 家庭月收入
        sb.append("0" + ReportingConstant.separator_union);
        //50 是否农户
        sb.append("0" + ReportingConstant.separator_union);
        //51 开户日期
        sb.append("" + ReportingConstant.separator_union);
        //52 信用级别
        sb.append("" + ReportingConstant.separator_union);
        //53 信用级别总等级数
        sb.append("" + ReportingConstant.separator_union);
        //54 违约概率（PD）
        sb.append("0" + ReportingConstant.separator_union);
        //55 违约损失率（LGD）
        sb.append("0" + ReportingConstant.separator_union);
        //56 违约风险暴露（EAD）
        sb.append("0" + ReportingConstant.separator_union);
        //57 非预期损失（UL）
        sb.append("0" + ReportingConstant.separator_union);
        if(null != bankcardInfo){
            //58 绑定银行卡卡号
            sb.append(bankcardInfo.getCardNumber() + ReportingConstant.separator_union);
        }else{
            //58 绑定银行卡卡号
            sb.append("" + ReportingConstant.separator_union);
        }
        //59 绑定银行卡开户行号
        sb.append("" + ReportingConstant.separator_union);
        //60 客户状态
        sb.append("1" + ReportingConstant.separator_union);
        //61 源系统标识
        SystemParameterRes source = systemParameterService.findByParamCode(ReportingConstant.SYS_SOURCE_ID,secondLevel.getTenantId());
        sb.append(source.getParamValue());

        return sb.toString();
    }

    @Override
    public String createRisManagementFileMessage(TlLoanClassifyChange tlLoanClassifyChange) throws TxnException {
        AmLoanMainInfo mainInfo = extAmLoanMainInfoMapper.selectByLoanIdAndCusId(tlLoanClassifyChange.getLoanId(),tlLoanClassifyChange.getCustomerId(),tlLoanClassifyChange.getTenantId());
        PrProductTable productTable = productTableService.findProByProIdAndOrgId(mainInfo.getProductId(),mainInfo.getOrganizationId(),mainInfo.getTenantId());
        AmLoanAccountInfo accountInfo = extAmLoanAccountInfoMapper.selectByLoanId(mainInfo.getLoanId(),mainInfo.getCustomerId(),mainInfo.getTenantId());

        String isClear = "";
        TlLoanClassifyChange preClass = extTlLoanClassifyChangeMapper.selectPreMessage(tlLoanClassifyChange.getTenantId(),tlLoanClassifyChange.getCustomerId(),tlLoanClassifyChange.getLoanId(),tlLoanClassifyChange.getBusinessDate());
        if(ReportingConstant.ACCOUNT_STATUS_7.equals(accountInfo.getAccountStatus())||
                ReportingConstant.ACCOUNT_STATUS_8.equals(accountInfo.getAccountStatus())){
            isClear = ReportingConstant.YES_FLAG;
        }else{
            isClear = ReportingConstant.NO_FLAG;
        }

        int delqDays = 0;

        StringBuffer sb = new StringBuffer();
        //1 租户号
        sb.append(tlLoanClassifyChange.getTenantId() + ReportingConstant.separator_union);
        //2 借据号
        sb.append(subLoanId(tlLoanClassifyChange.getLoanId(),tlLoanClassifyChange.getTenantId()) + ReportingConstant.separator_union);
        //3 用户编号
        sb.append(handleCustomerId(tlLoanClassifyChange.getCustomerId(),tlLoanClassifyChange.getTenantId()) + ReportingConstant.separator_union);
        //4 商户Id
        SystemParameterRes merchantRes = systemParameterService.findByParamCode(ReportingConstant.SYS_MERCHANT_ID,tlLoanClassifyChange.getTenantId());
        sb.append(merchantRes.getParamValue() + ReportingConstant.separator_union);
        //5 产品NO
        if(ReportingConstant.UNION_DEFAULT_TENANT_ID.equals(tlLoanClassifyChange.getTenantId())){
            SystemParameterRes prodRes = systemParameterService.findByParamCode(ReportingConstant.SYS_PRODUCT_ID,tlLoanClassifyChange.getTenantId());
            sb.append(prodRes.getParamValue() + ReportingConstant.separator_union);
        }else{
            sb.append(productTable.getProductId() + ReportingConstant.separator_union);
        }
        //6 产品Id
        sb.append(productTable.getId() + ReportingConstant.separator_union);
        //7 产品名称
        sb.append(productTable.getChineseName() + ReportingConstant.separator_union);
        //8 门店Id
        sb.append("" + ReportingConstant.separator_union);
        //9 逾期天数
        if(isClear.equals(ReportingConstant.NO_FLAG)){
            sb.append((accountInfo.getDelqDays()==0?"":accountInfo.getDelqDays()) + ReportingConstant.separator_union);
            delqDays = accountInfo.getDelqDays();
        }else{
            //结清的还是用上一次的逾期天数
            if(null != preClass){
                sb.append((preClass.getDelqDays()==0?"":preClass.getDelqDays()) + ReportingConstant.separator_union);
                delqDays = preClass.getDelqDays();
            }else{
                sb.append("" + ReportingConstant.separator_union);
            }
        }
        //10 逾期罚息（废弃）
        sb.append("0" + ReportingConstant.separator_union);
        //11 逾期罚息（废弃）
        sb.append("0" + ReportingConstant.separator_union);
        //12  五级分类标志 EnumFiveLevel 1:正常2:关注3:次级4:可疑5:损失
        int loanClassify = Integer.parseInt(tlLoanClassifyChange.getAfterStatus()) + 1;
        sb.append(loanClassify + ReportingConstant.separator_union);

        String accountingPhase = "";
        if(delqDays == 0){
            accountingPhase = ReportingConstant.TAIAN_ACCOUNTING_PHASE_1;
        }else if(delqDays >= 1 && delqDays <= 90){
            accountingPhase = ReportingConstant.TAIAN_ACCOUNTING_PHASE_2;
        }else if(delqDays > 90 && delqDays <= 180){
            accountingPhase = ReportingConstant.TAIAN_ACCOUNTING_PHASE_3;
        } else if (delqDays > 180) {
            accountingPhase = ReportingConstant.TAIAN_ACCOUNTING_PHASE_4;
        }

        //13 四级分类标志 EnumFourLevel 1:正常2:逾期3:呆滞4:呆账
        sb.append(accountingPhase + ReportingConstant.separator_union);
        //14 认定时间
        sb.append("" + ReportingConstant.separator_union);
        //15 认定类型EnumCognizanceType: 0:系统 1:人工
        sb.append("0" + ReportingConstant.separator_union);
        //16 是否进行回归认定EnumBool: 0:否 1:是
        sb.append("1" + ReportingConstant.separator_union);
        //17 连续正常还款次数
        sb.append("0" + ReportingConstant.separator_union);
        //18 上一次呆账储备金（减至）
        sb.append("0" + ReportingConstant.separator_union);
        //19 创建时间
        sb.append("" + ReportingConstant.separator_union);
        //20 更新时间
        sb.append(DateUtils.format(tlLoanClassifyChange.getCreateTime(),DateUtils.DATE_PATTERN_ANOTHER) + ReportingConstant.separator_union);
        //21 是否已结清 EnumBool 0:否 1:是
        sb.append(isClear + ReportingConstant.separator_union);
        //22 源系统标识
        SystemParameterRes sourceRes = systemParameterService.findByParamCode(ReportingConstant.SYS_SOURCE_ID,tlLoanClassifyChange.getTenantId());
        sb.append(sourceRes.getParamValue() + ReportingConstant.separator_union);
        //23 业务办理机构
        SystemParameterRes orgRes = systemParameterService.findByParamCode(ReportingConstant.SYS_ORGNO,tlLoanClassifyChange.getTenantId());
        sb.append(orgRes.getParamValue() + ReportingConstant.separator_union);

        SystemParameterRes aclgNo = null;//正常放款科目
        SystemParameterRes aclgNo59201 = null;//逾期还款科目
        SystemParameterRes aclgNo59301 = null;//90天表外还款科目
        if(ReportingConstant.UNION_DEFAULT_TENANT_ID.equals(mainInfo.getTenantId())){
            aclgNo = systemParameterService.findByParamCode(ReportingConstant.TA_SYS_ACLG_NO,mainInfo.getTenantId());
            aclgNo59201 = systemParameterService.findByParamCode(ReportingConstant.TA_SYS_ACLG_NO_59201,tlLoanClassifyChange.getTenantId());
            aclgNo59301 = systemParameterService.findByParamCode(ReportingConstant.TA_SYS_ACLG_NO_59301,tlLoanClassifyChange.getTenantId());
        }else if(ReportingConstant.UNION_LS_TENANT_ID.equals(mainInfo.getTenantId())){
            //需要区分经营 消费贷
            if(mainInfo.getLoanType().equals(ReportingConstant.LOAN_TYPE_6)){
                aclgNo = systemParameterService.findByParamCode(ReportingConstant.LS_SYS_ACLG_NO_JY,mainInfo.getTenantId());
                aclgNo59201 = systemParameterService.findByParamCode(ReportingConstant.LS_SYS_ACLG_NO_59201_JY,tlLoanClassifyChange.getTenantId());
                aclgNo59301 = systemParameterService.findByParamCode(ReportingConstant.LS_SYS_ACLG_NO_59301_JY,tlLoanClassifyChange.getTenantId());
            }else{
                aclgNo = systemParameterService.findByParamCode(ReportingConstant.LS_SYS_ACLG_NO_XF,mainInfo.getTenantId());
                aclgNo59201 = systemParameterService.findByParamCode(ReportingConstant.LS_SYS_ACLG_NO_59201_XF,tlLoanClassifyChange.getTenantId());
                aclgNo59301 = systemParameterService.findByParamCode(ReportingConstant.LS_SYS_ACLG_NO_59301_XF,tlLoanClassifyChange.getTenantId());
            }
        }

        //根据上期五级分类获取科目
        String subjectNo = getSubjectByPreClass(preClass,aclgNo.getParamValue(),aclgNo59201.getParamValue(),aclgNo59301.getParamValue());

        //新建订单和结清订单也会记录
        if(tlLoanClassifyChange.getDelqDays() == 0){
            //新增或者结清的订单
            if(ReportingConstant.NO_FLAG.equals(isClear)){
                //新建
                //24 原明细科目编号
                sb.append("" + ReportingConstant.separator_union);
                //25 原五级形态
                sb.append("" + ReportingConstant.separator_union);
                //26 新明细科目编号
                sb.append(aclgNo.getParamValue() + ReportingConstant.separator_union);
                //27 新五级形态
                sb.append(ReportingConstant.TAIAN_CLASSIFY_1 + ReportingConstant.separator_union);
                //28 转入金额 本金余额
                sb.append(tlLoanClassifyChange.getPrincipalAmount() + ReportingConstant.separator_union);
                //29 转出金额 上一笔的发生额
                sb.append("0" + ReportingConstant.separator_union);
            }else{
                //结清 泰安五级分类不可逆，临商五级分类可逆
                //24 原明细科目编号
                if(ReportingConstant.LOAN_CLASSIFY_0.equals(tlLoanClassifyChange.getAfterStatus())){
                    //24 原明细科目编号
                    sb.append(subjectNo + ReportingConstant.separator_union);
                    //25 原五级形态
                    sb.append(transFive(preClass.getAfterStatus()) + ReportingConstant.separator_union);
                    //26 新明细科目编号
                    sb.append(aclgNo.getParamValue() + ReportingConstant.separator_union);
                    //27 新五级形态
                    sb.append(ReportingConstant.TAIAN_CLASSIFY_1 + ReportingConstant.separator_union);
                    //28 转入金额 本金余额
                    sb.append(preClass.getPrincipalAmount() + ReportingConstant.separator_union);
                    //29 转出金额 上一笔的发生额
                    sb.append("0" + ReportingConstant.separator_union);
                }else if(ReportingConstant.LOAN_CLASSIFY_1.equals(tlLoanClassifyChange.getAfterStatus())){
                    //24 原明细科目编号
                    sb.append(subjectNo + ReportingConstant.separator_union);
                    //25 原五级形态
                    sb.append(transFive(preClass.getAfterStatus()) + ReportingConstant.separator_union);
                    //26 新明细科目编号
                    sb.append(aclgNo59201.getParamValue() + ReportingConstant.separator_union);
                    //27 新五级形态
                    sb.append(ReportingConstant.TAIAN_CLASSIFY_2 + ReportingConstant.separator_union);
                    //28 转入金额 本金余额
                    sb.append(preClass.getPrincipalAmount() + ReportingConstant.separator_union);
                    //29 转出金额 上一笔的发生额
                    sb.append(preClass.getPrincipalAmount() + ReportingConstant.separator_union);
                }else if(ReportingConstant.LOAN_CLASSIFY_2.equals(tlLoanClassifyChange.getAfterStatus())){
                    //24 原明细科目编号
                    sb.append(subjectNo + ReportingConstant.separator_union);
                    //25 原五级形态
                    sb.append(transFive(preClass.getAfterStatus()) + ReportingConstant.separator_union);
                    //26 新明细科目编号
                    sb.append(aclgNo59201.getParamValue() + ReportingConstant.separator_union);
                    //27 新五级形态
                    sb.append(ReportingConstant.TAIAN_CLASSIFY_3 + ReportingConstant.separator_union);
                    //28 转入金额 本金余额
                    sb.append(preClass.getPrincipalAmount() + ReportingConstant.separator_union);
                    //29 转出金额 上一笔的发生额
                    sb.append(preClass.getPrincipalAmount() + ReportingConstant.separator_union);
                }else if(ReportingConstant.LOAN_CLASSIFY_3.equals(tlLoanClassifyChange.getAfterStatus())){
                    //24 原明细科目编号
                    sb.append(subjectNo + ReportingConstant.separator_union);
                    //25 原五级形态
                    sb.append(transFive(preClass.getAfterStatus()) + ReportingConstant.separator_union);
                    //26 新明细科目编号
                    sb.append(aclgNo59301.getParamValue() + ReportingConstant.separator_union);
                    //27 新五级形态
                    sb.append(ReportingConstant.TAIAN_CLASSIFY_4 + ReportingConstant.separator_union);
                    //28 转入金额 本金余额
                    sb.append(preClass.getPrincipalAmount() + ReportingConstant.separator_union);
                    //29 转出金额 上一笔的发生额
                    sb.append(preClass.getPrincipalAmount() + ReportingConstant.separator_union);
                }else{
                    //24 原明细科目编号
                    sb.append(subjectNo + ReportingConstant.separator_union);
                    //25 原五级形态
                    sb.append(transFive(preClass.getAfterStatus()) + ReportingConstant.separator_union);
                    //26 新明细科目编号
                    sb.append(aclgNo59301.getParamValue() + ReportingConstant.separator_union);
                    //27 新五级形态
                    sb.append(ReportingConstant.TAIAN_CLASSIFY_5 + ReportingConstant.separator_union);
                    //28 转入金额 本金余额
                    sb.append(preClass.getPrincipalAmount() + ReportingConstant.separator_union);
                    //29 转出金额 上一笔的发生额
                    sb.append(preClass.getPrincipalAmount() + ReportingConstant.separator_union);
                }
            }
        }else if (tlLoanClassifyChange.getDelqDays() >= 1 && tlLoanClassifyChange.getDelqDays() <= 90){
            //24 原明细科目编号
            sb.append(subjectNo + ReportingConstant.separator_union);
            //25 原五级形态
            sb.append(ReportingConstant.TAIAN_CLASSIFY_1 + ReportingConstant.separator_union);
            //26 新明细科目编号
            sb.append(aclgNo59201.getParamValue() + ReportingConstant.separator_union);
            //27 新五级形态
            sb.append(ReportingConstant.TAIAN_CLASSIFY_2 + ReportingConstant.separator_union);
            //28 转入金额 本金余额
            sb.append(tlLoanClassifyChange.getPrincipalAmount() + ReportingConstant.separator_union);
            //29 转出金额 上一笔的发生额
            sb.append("0" + ReportingConstant.separator_union);
        }else if (tlLoanClassifyChange.getDelqDays() >= 91 && tlLoanClassifyChange.getDelqDays() <= 180){
            //24 原明细科目编号
            sb.append(subjectNo + ReportingConstant.separator_union);
            //25 原五级形态
            sb.append(ReportingConstant.TAIAN_CLASSIFY_2 + ReportingConstant.separator_union);
            //26 新明细科目编号
            sb.append(aclgNo59201.getParamValue() + ReportingConstant.separator_union);
            //27 新五级形态
            sb.append(ReportingConstant.TAIAN_CLASSIFY_3 + ReportingConstant.separator_union);
            //28 转入金额 本金余额
            sb.append(tlLoanClassifyChange.getPrincipalAmount() + ReportingConstant.separator_union);
            //29 转出金额 上一笔的发生额
            sb.append("0" + ReportingConstant.separator_union);
        }else if (tlLoanClassifyChange.getDelqDays() >= 181 && tlLoanClassifyChange.getDelqDays() <= 360){
            //24 原明细科目编号
            sb.append(subjectNo + ReportingConstant.separator_union);
            //25 原五级形态
            sb.append(ReportingConstant.TAIAN_CLASSIFY_3 + ReportingConstant.separator_union);
            //26 新明细科目编号
            sb.append(aclgNo59301.getParamValue() + ReportingConstant.separator_union);
            //27 新五级形态
            sb.append(ReportingConstant.TAIAN_CLASSIFY_4 + ReportingConstant.separator_union);
            //28 转入金额 本金余额
            sb.append(tlLoanClassifyChange.getPrincipalAmount() + ReportingConstant.separator_union);
            //29 转出金额 上一笔的发生额
            sb.append("0" + ReportingConstant.separator_union);
        }else if (tlLoanClassifyChange.getDelqDays() >= 361){
            //24 原明细科目编号
            sb.append(subjectNo + ReportingConstant.separator_union);
            //25 原五级形态
            sb.append(ReportingConstant.TAIAN_CLASSIFY_4 + ReportingConstant.separator_union);
            //26 新明细科目编号
            sb.append(aclgNo59301.getParamValue() + ReportingConstant.separator_union);
            //27 新五级形态
            sb.append(ReportingConstant.TAIAN_CLASSIFY_5 + ReportingConstant.separator_union);
            //28 转入金额 本金余额
            sb.append(tlLoanClassifyChange.getPrincipalAmount() + ReportingConstant.separator_union);
            //29 转出金额 上一笔的发生额
            sb.append("0" + ReportingConstant.separator_union);
        }

        //30 经办员工号
        SystemParameterRes custMgNo = systemParameterService.findByParamCode(ReportingConstant.SYS_CUST_MG_NO,tlLoanClassifyChange.getTenantId());
        sb.append(custMgNo.getParamValue() + ReportingConstant.separator_union);
        //31 授权员工号
        sb.append(custMgNo.getParamValue() + ReportingConstant.separator_union);
        //32 审批员工号
        sb.append(custMgNo.getParamValue() + ReportingConstant.separator_union);
        //33 变动原因
        sb.append("" + ReportingConstant.separator_union);
        //34 变动方式
        sb.append("" );

        return sb.toString();
    }

    @Override
    public void generateUnionFile(List<String> messageList, String reportingPath, String fileName, String fileType) throws TxnException {
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);
        String toDay = DateUtils.format(org.getToday(),"yyyyMMdd");

        String collectionFileName = "";
        if(ReportingConstant.UNION_LS_TENANT_ID.equals(org.getTenantId())){
            collectionFileName = "JLCLOUD_" + fileType+ "_" + toDay + "_" + fileName + ".del";
        }else{
            collectionFileName = fileType+ "_" + toDay + "_" + fileName + ".del";
        }


        String filePath = reportingPath + org.getTenantId() + File.separator + toDay + File.separator;

        Path reportingFile = Paths.get(filePath + collectionFileName);

        String charSet = "UTF-8";
        if(ReportingConstant.UNION_LS_TENANT_ID.equals(org.getTenantId())){
            charSet = "GBK";
        }

        FileUtils.writeFile(reportingFile.toString(), messageList, charSet);
    }

    @Override
    public void mergeFile(PrOrganizationTable org, String filePath) throws IOException {
        logger.info("开始合并分库文件");
        Date bussinessDate = org.getToday();
        String toDay = DateUtils.format(bussinessDate,"yyyyMMdd");
        String reportingPath = filePath + org.getTenantId() + File.separator + toDay + File.separator;

        //生成验签文件
        Path reportingFile = Paths.get(reportingPath + "indicate.txt");
        try {
            Files.createFile(reportingFile);
        } catch (IOException e) {
            logger.error("创建联盟验签文件失败",e);
        }

        //生成联盟放款流水文件 记录验签信息
        mergeUnionFile(reportingPath,ReportingConstant.UNION_FILE_TYPE_LOAN_SERJAR,toDay,org);

        //生成客户信息文件
        mergeUnionFile(reportingPath,ReportingConstant.UNION_FILE_TYPE_CUSTOMER_INFO,toDay,org);

        //生成授信文件
        mergeUnionFile(reportingPath,ReportingConstant.UNION_FILE_TYPE_CREDIT_INFO,toDay,org);

        //生成联系点文件
        mergeUnionFile(reportingPath,ReportingConstant.UNION_FILE_TYPE_USER_CONTACT,toDay,org);

        //生成借据产品信息
        mergeUnionFile(reportingPath,ReportingConstant.UNION_FILE_TYPE_LOAN_PRODUCT,toDay,org);

        //生成还款流水
        mergeUnionFile(reportingPath,ReportingConstant.UNION_FILE_TYPE_REPAY_SERIAL,toDay,org);

        //生成借据信息
        mergeUnionFile(reportingPath,ReportingConstant.UNION_FILE_TYPE_LOAN_INFO,toDay,org);

        //生成证件文档
        mergeUnionFile(reportingPath,ReportingConstant.UNION_FILE_TYPE_CERTIFICATE_INFO,toDay,org);

        //生成计提流水
        mergeUnionFile(reportingPath,ReportingConstant.UNION_FILE_TYPE_ACCRUED_SERIAL,toDay,org);

        //生成合同信息表
        mergeUnionFile(reportingPath,ReportingConstant.UNION_FILE_TYPE_CONTRACT_INFO,toDay,org);

        //生成还款计划
        mergeUnionFile(reportingPath,ReportingConstant.UNION_FILE_TYPE_REPAY_PLAN,toDay,org);

        //生成地址联系点
        mergeUnionFile(reportingPath,ReportingConstant.UNION_FILE_TYPE_ADDRESS,toDay,org);

        //生成客户资源关系
        mergeUnionFile(reportingPath,ReportingConstant.UNION_FILE_TYPE_CUSTOMER_RESOURCE,toDay,org);

        //生成电话联系点
        mergeUnionFile(reportingPath,ReportingConstant.UNION_FILE_TYPE_TEL,toDay,org);

        //生成个人客户
        mergeUnionFile(reportingPath,ReportingConstant.UNION_FILE_TYPE_PERSONAL_BASIC,toDay,org);

        //生成风控信息
        mergeUnionFile(reportingPath,ReportingConstant.UNION_FILE_TYPE_RISK_MANAGEMENT,toDay,org);

    }

    @Override
    public void compressFile(PrOrganizationTable org, String filePath, String outFilePath, String nftsPath) throws IOException {
        String toDay = DateUtils.format(org.getToday(),"yyyyMMdd");

        String reportingPath = "";
        if(ReportingConstant.UNION_LS_TENANT_ID.equals(org.getTenantId())){
            reportingPath = filePath + org.getTenantId() + File.separator + toDay + File.separator + "JLCLOUD_";
        }else{
            reportingPath = filePath + org.getTenantId() + File.separator + toDay + File.separator;
        }

        List<File> sources = new ArrayList<>();
        sources.add(new File(reportingPath + ReportingConstant.UNION_FILE_TYPE_LOAN_SERJAR +".del"));
        sources.add(new File(reportingPath + ReportingConstant.UNION_FILE_TYPE_CUSTOMER_INFO +".del"));
        sources.add(new File(reportingPath + ReportingConstant.UNION_FILE_TYPE_CREDIT_INFO +".del"));
        sources.add(new File(reportingPath + ReportingConstant.UNION_FILE_TYPE_USER_CONTACT +".del"));
        sources.add(new File(reportingPath + ReportingConstant.UNION_FILE_TYPE_LOAN_PRODUCT +".del"));
        sources.add(new File(reportingPath + ReportingConstant.UNION_FILE_TYPE_REPAY_SERIAL +".del"));
        sources.add(new File(reportingPath + ReportingConstant.UNION_FILE_TYPE_LOAN_INFO +".del"));
        sources.add(new File(reportingPath + ReportingConstant.UNION_FILE_TYPE_CERTIFICATE_INFO +".del"));
        sources.add(new File(reportingPath + ReportingConstant.UNION_FILE_TYPE_ACCRUED_SERIAL +".del"));
        sources.add(new File(reportingPath + ReportingConstant.UNION_FILE_TYPE_CONTRACT_INFO +".del"));
        sources.add(new File(reportingPath + ReportingConstant.UNION_FILE_TYPE_REPAY_PLAN +".del"));
        sources.add(new File(reportingPath + ReportingConstant.UNION_FILE_TYPE_ADDRESS +".del"));
        sources.add(new File(reportingPath + ReportingConstant.UNION_FILE_TYPE_CUSTOMER_RESOURCE +".del"));
        sources.add(new File(reportingPath + ReportingConstant.UNION_FILE_TYPE_TEL +".del"));
        sources.add(new File(reportingPath + ReportingConstant.UNION_FILE_TYPE_PERSONAL_BASIC +".del"));
        sources.add(new File(reportingPath + ReportingConstant.UNION_FILE_TYPE_RISK_MANAGEMENT +".del"));
        sources.add(new File(filePath + org.getTenantId() + File.separator + toDay + File.separator + "indicate.txt"));

        String tarFile = "";
        if(ReportingConstant.UNION_LS_TENANT_ID.equals(org.getTenantId())){
            //临商
            tarFile = outFilePath + org.getTenantId() + File.separator + toDay + File.separator + "JLCLOUD_" + org.getTenantId() + "_" + toDay + ".tar";
        }else{
            //泰安
            tarFile = outFilePath + org.getTenantId() + File.separator + toDay + File.separator + toDay + "_" + org.getTenantId() + ".tar";
        }

        File target = new File(tarFile);
        //生成压缩文件
        TargzUtil.pack(sources,target,outFilePath,toDay,org);

        //生成OK文件
        Path reportingFile;
        if(ReportingConstant.UNION_LS_TENANT_ID.equals(org.getTenantId())){
            reportingFile = Paths.get(outFilePath + org.getTenantId() + File.separator + toDay + File.separator + "JLCLOUD_" + org.getTenantId() + "_" + toDay + ".ok");
        }else{
            reportingFile = Paths.get(outFilePath + org.getTenantId() + File.separator + toDay + File.separator + toDay + "_" + org.getTenantId() + ".ok");
        }
        try {
            Files.createFile(reportingFile);
        } catch (IOException e) {
            logger.error("创建联盟OK失败",e);
            throw new RuntimeException("创建联盟OK失败");

        }

        //文件传输
        String outPath = outFilePath + org.getTenantId() + File.separator + toDay + File.separator;
        //业务文件类型代码
        String bizFtypeCode = "";
        if(ReportingConstant.UNION_DEFAULT_TENANT_ID.equals(org.getTenantId())){
            bizFtypeCode = "s_anyrcs_rptdata";
        }else if(ReportingConstant.UNION_LS_TENANT_ID.equals(org.getTenantId())){
            bizFtypeCode = "s_anyrcs_jlcloud";
        }
        try {
            createTskdFileSampleSimple.initNfsTransFile(outPath, nftsPath, "", bizFtypeCode ,org.getTenantId(),toDay,"0");
        } catch (Exception e1) {
            logger.error("文件传输失败",e1);
            throw new RuntimeException("文件传输失败");
        }
    }


    //根据身份证计算年龄
    private int getAge(String cardId){
        Calendar ca = Calendar.getInstance();
        int nowYear= ca.get(Calendar.YEAR);
        int nowMonth= ca.get(Calendar.MONTH)+1;
        int len=cardId.length();
        if(len==18){
            int IDYear= Integer.parseInt(cardId.substring(6, 10));
            int IDMonth= Integer.parseInt(cardId.substring(10, 12));
            if((IDMonth-nowMonth)>0){
                return nowYear-IDYear-1;
            }
            else
                return nowYear-IDYear;
        }
        else
            throw new RuntimeException("错误的身份证号, "+cardId);
    }

    private void mergeUnionFile(String reportingPath,String fileType,String today,PrOrganizationTable org)  {

        if(ReportingConstant.UNION_LS_TENANT_ID.equals(org.getTenantId())){
            fileType = "JLCLOUD_" + fileType;
        }

        //获取目录下所有文件
        File file = new File(reportingPath);
        File[] tempList = file.listFiles();
        if(tempList == null || tempList.length == 0){
            logger.error("文件合并，未获取到需要合并的文件");
            throw new RuntimeException("文件合并，未获取到需要合并的文件");
        }

        List<File> mergeList = new ArrayList<>();

        for(int i = 0; i < tempList.length; i++){
            String fileName = tempList[i].getName();
            if(fileType.length()>fileName.length()){
                continue;
            }
            String subStr = fileName.substring(0,fileType.length());
            if(fileType.equals(subStr)){
                mergeList.add(tempList[i]);
            }
        }

        //合并文件
        File resultFile = new File(reportingPath + fileType + ".del");

        Boolean isNullFile = true;
        try(FileChannel resultFileChannel= new FileOutputStream(resultFile, true).getChannel()){
            for(int i = 0; i < mergeList.size(); i++){
                FileChannel blk1 = new FileInputStream(mergeList.get(i)).getChannel();
                if(i == 0 && blk1.size() == 0){
                    resultFile.createNewFile();
                }else if (blk1.size() != 0){
                    if(!isNullFile && i != 0){
                        //换行
                        ByteBuffer buf = ByteBuffer.allocate(48);
                        buf.clear();
                        buf.put("\r\n".getBytes());
                        buf.flip();
                        while(buf.hasRemaining()) {
                            resultFileChannel.write(buf);
                        }
                    }
                    //写入新文件
                    resultFileChannel.transferFrom(blk1, resultFileChannel.size(), blk1.size());
                    isNullFile = false;
                }
                blk1.close();
            }
        } catch (IOException e) {
            logger.error("联盟文件合并异常，异常信息：",e);
            throw new RuntimeException(e);
        }

        String charSet = "UTF-8";
        if(ReportingConstant.UNION_LS_TENANT_ID.equals(org.getTenantId())){
            charSet = "GBK";
        }

        //记录验签数据
        File indicateFile = new File(reportingPath + "indicate.txt");
        String wirt = "";
        String huanh = "\r\n";
        try (BufferedWriter out = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(indicateFile,true), charSet))){
            FileReader fileReader = new FileReader(resultFile);
            LineNumberReader LineNumberReader = new LineNumberReader(fileReader);
            LineNumberReader.skip(Long.MAX_VALUE);
            fileReader.close();
            int lines = 0;
            if(resultFile.length() != 0){
                lines = LineNumberReader.getLineNumber() + 1;
            }
            LineNumberReader.close();
            String cksum = exeCmd("cksum " + resultFile);
            String ck[]=cksum.split(" ");
            wirt = today + " " + org.getTenantId() + " " + fileType + ".del" + " " +lines + " " + resultFile.length() + " " + ck[0];
            out.write(wirt + huanh);
            out.flush();
        } catch (IOException e) {
            logger.error("写入验签信息异常，异常信息：",e);
            throw new RuntimeException(e);
        }
    }

    public static String exeCmd(String commandStr) throws IOException {
        String[] cmd = new String[]{"/bin/sh", "-c", commandStr};
        Process ps = Runtime.getRuntime().exec(cmd);
        BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) {
            //执行结果加上回车
            sb.append(line).append("\n");
        }
        return sb.toString();
    }

    private String transFive(String five){
        switch (five){
            case ReportingConstant.LOAN_CLASSIFY_0:
                return ReportingConstant.TAIAN_CLASSIFY_1;
            case ReportingConstant.LOAN_CLASSIFY_1:
                return ReportingConstant.TAIAN_CLASSIFY_2;
            case ReportingConstant.LOAN_CLASSIFY_2:
                return ReportingConstant.TAIAN_CLASSIFY_3;
            case ReportingConstant.LOAN_CLASSIFY_3:
                return ReportingConstant.TAIAN_CLASSIFY_4;
            default:
                return ReportingConstant.TAIAN_CLASSIFY_5;
        }
    }

    private String handleCustomerId(String customerId,String tenantId){
        //只有泰安的需要特殊处理
        if(StringUtils.isNotBlank(customerId) && ReportingConstant.UNION_DEFAULT_TENANT_ID.equals(tenantId)){
            if (customerId.length() <= 5) {
                String custId = '1' + StringUtils.getLengthStr(customerId, 9, '0');
                custId = StringUtils.getLengthStr(custId, 16, '0');
                return custId;
            } else if(customerId.length()>5 && customerId.length()<16){
                return StringUtils.getLengthStr(customerId, 16, '0');
            }else {
                return customerId;
            }
        }
        return customerId;
    }

    private String getLastPaymentSeqNo(String loanId,String customerId,String tenantId){
        String paymenSeqno = extTlPaymentMappingMapper.findLastByCustomerIdAndLoanId(loanId,customerId,tenantId);
        TlPaymentLog tlPaymentLog = null;
        if(null != paymenSeqno){
            tlPaymentLog = extTlPaymentLogMapper.selectBySeqNoAndTenantIdAndCust(paymenSeqno,tenantId,customerId);
        }

        TlThirdPartyPayment tlThirdPartyPayment = extTlThirdPartyPaymentMapper.findLastByCustomerIdAndLoanId(loanId,customerId,tenantId);

        if(null == tlPaymentLog && null == tlThirdPartyPayment){
            return "";
        }else if(null != tlPaymentLog && null == tlThirdPartyPayment){
            return tlPaymentLog.getSeqNo();
        }else if(null == tlPaymentLog && null != tlThirdPartyPayment){
            return tlThirdPartyPayment.getSeqNo();
        }else{
            if(tlPaymentLog.getUpdateTime().compareTo(tlThirdPartyPayment.getUpdateTime()) >= 0){
                return tlPaymentLog.getSeqNo();
            }else{
                return tlThirdPartyPayment.getSeqNo();
            }
        }
    }

    //根据五级分类获取对应科目
    private String getSubjectByPreClass(TlLoanClassifyChange tlLoanClassifyChange,String aclgNo,String aclgNo59201,String aclgNo59301){
        String subject = "";
        if(null == tlLoanClassifyChange){
            return subject;
        }

        if(ReportingConstant.LOAN_CLASSIFY_0.equals(tlLoanClassifyChange.getAfterStatus())){
            subject = aclgNo;
        }else if(ReportingConstant.LOAN_CLASSIFY_1.equals(tlLoanClassifyChange.getAfterStatus())||
                    ReportingConstant.LOAN_CLASSIFY_2.equals(tlLoanClassifyChange.getAfterStatus())){
            subject = aclgNo59201;
        }else{
            subject = aclgNo59301;
        }
        return subject;
    }

    //字符串逗号空格处理
    private String handleAddress(String s) {
        if (StringUtils.isNotBlank(s)) {
            s = s.replaceAll("[\\pZ,，]", "-");
            if (s.contains(" ")) {
                s = s.replace(" ", "");
            }
        }
        return s;
    }
}
